我尝试使用preg_match_all()函数查找文本中所有出现的子字符串:
<?php
$str = '<p>this <a href="https://api.slack.com/apps/" target="_blank">link</a> and <a href="https://www.google.com" target="_blank">link 2</a></p>';
$reg = '/<a.*href="([^"]+)"[^>]+>(.+)</a>/';
preg_match_all($reg, $str, $m);
print_r($m);
但是上面的代码只返回最后一个链接:
当我将源文本分割成行时,相同的代码返回所有匹配项:
<?php
$str = '<p>this <a href="https://api.slack.com/apps/" target="_blank">link</a> and
the <a href="https://www.google.com" target="_blank">link 2</a></p>';
$reg = '/<a.*href="([^"]+)"[^>]+>(.+)</a>/';
preg_match_all($reg, $str, $m);
print_r($m);
PHP sandbox here
问题出在正则表达式上。您可以限制字符:
/<as*href="([^"]+)"[^>]+>([^<]+)</a>/
或者使用延迟匹配:
/<a.*?href="([^"]+)"[^>]+>(.+?)</a>/