你的代码
$matches = array();
$search="domain.com";
preg_match('|(<a\s*[^>]*href=[\'"]?)|',$prod['value'],$matches);
echo '<p>'.$matches[1].'</p>';
首先,$matches不需要在preg_match调用之前定义。您只需要提供一个变量名,并且PHP不会抛出一个通知。
其次,$search似乎与问题无关?...
第三...请记住,您没有显示示例输入,我将假设您确实想要preg_match_all这样,以便您可以URLs从输入中获取所有内容的列表。
第四,从三开始,这意味着您需要var_dumporprint_r而不是echo作为内容的$matches[X]将是一个array.
正则表达式
好的,现在你的正则表达式模式实际上做了什么......
(<a\s*[^>]*href=['"]?)
(- 启动一个捕获组
<a\s*- 匹配<a后跟0 个或多个空格字符
[^>]*- 匹配0 个或多个非字符>
href=- 火柴href=
['"]?- 可选地匹配'或"
)- 结束捕获组
这一切都意味着针对示例输入<a href="运行您的正则表达式将从第一个链接示例(google)和<a class="fancyStyle" href="第二个链接示例(youtube)匹配。
/**
Output from:
preg_match_all('|(<a\s*[^>]*href=[\'"]?)|', $string, $matches);
var_dump($matches);
*/
array(2) {
[0]=>
array(2) {
[0]=>
string(9) "<a href=""
[1]=>
string(28) "<a class="fancyStyle" href=""
}
[1]=>
array(2) {
[0]=>
string(9) "<a href=""
[1]=>
string(28) "<a class="fancyStyle" href=""
}
}
工作代码
您的代码存在一些问题,但是,阻止您获得预期结果的问题URL是您只是在到达之前停止捕获。
以下正则表达式将匹配标签属性URL内的 s 。hrefa
#<a\s.*?(?:href=['"](.*?)['"]).*?>#is
解释
<a- 匹配a标签的开头
\s.*?- 匹配空格字符后跟任意字符0 次或更多次
(?:- 创建一个非捕获组
href=- 火柴href=
['"]- 匹配'或"
(.*?)- 创建一个捕获组并匹配之前的0 个或多个字符...
['"]- 匹配'或"
)- 结束非捕获组
.*?>- 匹配任何字符0 次或多次,后跟>
i- 使正则表达式不区分大小写
s-.匹配所有字符(包括换行符)
工作示例
preg_match_all('#<a\s.*?(?:href=[\'"](.*?)[\'"]).*?>#is', $string, $matches);
var_dump($matches);
/**
array(2) {
[0]=>
array(2) {
[0]=>
string(34) "<a href="http://www.google.co.uk">"
[1]=>
string(65) "<a class="fancyStyle" href="http://www.youtube.com" id="link136">"
}
[1]=>
array(2) {
[0]=>
string(23) "http://www.google.co.uk"
[1]=>
string(22) "http://www.youtube.com"
}
}
*/
示例输入
所有代码都使用以下作为preg_match函数的输入...
$string = <<<EOC
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title of page</title>
</head>
<body>
<h1>Main Page title</h1>
<p>
The following is a <a href="http://www.google.co.uk">link to google</a>.
This is <a class="fancyStyle" href="http://www.youtube.com" id="link136">another link</a>
</p>
</body>
</html>
EOC;