我有一个表单,其中将插入带有网址的文本。我已经有了正则表达式验证规则t搜索网址。此规则将替换指向其他文本的web链接。但我的任务是编写一个函数,将所有这些地址保存到数组中。如何将所有这些地址保存到数组中?
这是我现在的代码:
<html>
<head>
<meta charset="UTF-8">
<title>Expressions: Find web address in text</title>
</head>
<body>
<?php
/*--------Functions---------*/
function webCheck($webtext){
global $web_check;
$web_check = "/((http:'/'/www'.)|(http:'/'/)|(www'.))([a-z0-9]+([a-z0-9-]*[a-z0-9]+)*'.)+[a-z]+/i";
return preg_replace($web_check, "<b>was weblink here</b>", $webtext);
}
/*--------End of Functions----------*/
if(isset($_POST["webadd"])){
$webtext = $_POST["webtext"];
if (!empty($webtext)){
echo webCheck($webtext);
}else{
echo "Feald cannot be empty. Please enter some text.";
}
} else {
echo "Please enter text in text area.";
}
?>
<form action="expression3.php" method="POST">
<table>
<tr>
<td>Find web address in text</td>
</tr>
<tr>
<td> <textarea name="webtext" cols="50" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="webadd" value="Find Web Address!" /></td>
</tr>
</table>
</form>
</body>
只需使用如下的推送函数,就可以将任何内容存储到数组中:
$my_links_array = array();
array_push($my_links_array, webCheck($webtext));
或通过:
$array[] = webCheck($webtext);
这对你来说实际上是一样的,但被认为更快的
您可以使用preg_replace_callback来执行闭包中的代码:
$myarr = array();
return preg_replace_callback($web_check,
function ($m) use (&$myarr) {
$myarr[] = $m[0];
return '<b>was weblink here</b>';
}, $webtext);
请注意,要更改闭包中的变量,需要通过引用传递它。
尝试。。
/*--------Functions---------*/
$arrWebAddreses = array();
function webCheck($webtext){
global $web_check;
$web_check = "/((http:'/'/www'.)|(http:'/'/)|(www'.))([a-z0-9]+([a-z0-9-]*[a-z0-9]+)*'.)+[a-z]+/i";
$matches = array();
preg_match($web_check, $webtext, $matches);
if(count($matches)>0)
$arrWebAdresses += $matches[0];
return preg_replace($web_check, "<b>was weblink here</b>", $webtext);
}
/*--------End of Functions----------*/