【发布时间】:2016-06-14 14:08:00
【问题描述】:
这有点让我困惑,我似乎不明白为什么http://www.example.com/a/b/c 会返回https://example.net//b/c - 最好的猜测是它与第一场比赛冲突,但为什么呢?
代码:
$contents = '
<a href="http://www.example.com/a">Works</a>
<a href="http://www.example.com/a/b/c">Doesnt Work</a>
<a href="http://www.example.com/x/y/z">Works</a>';
$regexp = "/<a\s[^>]*href=\"([^\"]*)\"[^>]*>(.*)<\/a>/siU";
if(preg_match_all($regexp, $contents, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
print_r($match);
if (!empty($match[1])) {
$urlString = 'https://www.example.net/newlink/';
$contents = str_replace($match[1], $urlString, $contents);
}
}
}
echo $contents;
输出:
Array
(
[0] => <a href="http://www.example.com/a">Works</a>
[1] => http://www.example.com/a
[2] => Works
)
Array
(
[0] => <a href="http://www.example.com/a/b/c">Doesnt Work</a>
[1] => http://www.example.com/a/b/c
[2] => Doesnt Work
)
Array
(
[0] => <a href="http://www.example.com/x/y/z">Works</a>
[1] => http://www.example.com/x/y/z
[2] => Works
)
<a href="https://www.example.net/newlink/">Works</a>
<a href="https://www.example.net/newlink//b/c">Doesnt Work</a>
<a href="https://www.example.net/newlink/">Works</a>
【问题讨论】:
-
在
preg_replace_callback中进行操作。问题是在第一次迭代期间在$contents中完成了 2 次替换,因为有 2 个http://www.example.com/a子字符串。 -
谢谢,会调查那个解决方案。
标签: php regex html-parsing