考虑以下情况:我想替换字符串中的链接,特别是在它旁边添加一个“搜索引擎”链接。
思考:链接标题,其中as s将链接到谷歌与“链接标题”作为搜索词。我在代码中复制了一个真实的示例字符串($content),这样您就可以在PHP代码中重现这个1:1。
// PCRE case-insensitive, all as a single string, ungreedy and evaluate PHP replace.
$content = '<h3 class="bgg2" style="padding: 4px 0px 4px 5px; font-size: 11px;">» <a href="/forum_detail.html?topic=3456&start=20&post=97145#p97145" class="nub" title="Xenoblade: Japanischer TV-Spot"><b>Xenoblade: Japanischer TV-Spot</b></a></h3>';
$replace = preg_replace('/(<a.*>)(.*)<\/a>/isUe', ('"\1\2</a> (<a href=\"http://www.google.com/search?q=' . strip_tags(strtoupper('blah\2')) . '\">S</a>)"'), $content);
print($replace);
输出(不正确):
Xenoblade:Japanischer TV SPOT(s)->当您查看HTML时,它看起来如下:
<a href="http://www.google.com/search?q=BLAH%3Cb%3EXenoblade:%20Japanischer%20TV-Spot%3C/b%3E">S</a>
strToUpper()没有从正则表达式中获取文本字符串blah->blah,但没有从\2返回引用?
似乎以前使用过\2后面引用的字符串
strtoupper()
或
strip_tags()
函数被执行——也许是某种评估时间与PHP中的函数的对比?
有人知道如何解释这种行为吗?
——
我开发了一个解决方法
preg_replace_callback
但是我还是很困惑为什么上面的代码不能像我预期的那样工作。
请参考我想要实现的目标:
解决方案
// I have to use PHP < 5.0 so create_function() will do the job.
$replace = preg_replace_callback('/(<a.*>)(.*)<\/a>/isU',
create_function('$matches', 'return $matches[1] . $matches[2] . \'</a> (<a href="http://www.google.com/search?q=\' . strip_tags(strtoupper($matches[2])) . \'">S</a>)\';'),
$content);
print($replace);
输出(正确):
Xenoblade:Japanischer TV SPOT(s)->当您查看HTML时,它看起来如下:
<a href="http://www.google.com/search?q=XENOBLADE:%20JAPANISCHER%20TV-SPOT">S</a>