我需要查找 http 链接并将其替换为超链接。这些 http 链接位于 span 标记内。
$text 有 html 页面。其中一个 span 标签有类似
<span class="styleonetwo" >http://www.cnn.com/live-event</span>
这是我的代码:
$doc = new DOMDocument();
$doc->loadHTML($text);
foreach($doc->getElementsByTagName('span') as $anchor) {
$link = $anchor->nodeValue;
if(substr($link, 0, 4) == "http")
{
$link = "<a href=\"$link\">$link</a>";
}
if(substr($link, 0, 3) == "www")
{
$link = "<a href=\"http://$link\">$link</a>";
}
$anchor->nodeValue = $link;
}
echo $doc->saveHTML();
工作正常。但是......我希望它能够工作,即使跨度内的数据类似于:
<span class="styleonetwo" > sometexthere http://www.cnn.com/live-event somemoretexthere</span>
显然上面的代码不适用于这种情况。有没有一种方法可以使用 DOMDocument 搜索和替换模式而不使用 preg_replace?
更新:回答 phil 有关 preg_replace 的问题:
我使用 regexpal.com 来测试以下模式匹配:
\b(?:(?:https?|ftp|file)://|(www|ftp)\.)[-A-Z0-9+&@#/%?=~_|$!:,.;]*[-A-Z0-9+&@#/%=~_|$]
它在 regexpal 提供的 regextester 中工作得很好。当我在 PHP 代码中使用相同的模式时,我遇到了大量奇怪的错误。即使对于转义字符,我也遇到了未知的修饰符错误!以下是我的 preg_replace 代码
$httpRegex = '/\b(\?:(\?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#/%\?=~_|$!:,.;]*[-A-Z0-9+&@#/%=~_|$]/';
$cleanText = preg_replace($httpRegex, "<a href='$0'>$0</a>", $text);
我对“未知修饰符”感到非常沮丧,并寻求 DOMDocument 来解决我的问题。
最佳答案
正则表达式非常适合这个问题 - 所以最好使用 preg_replace
。
现在你只有几个未转义的 delimiters在您的模式中,因此转义它们或选择另一个字符作为分隔符 - 例如,^
。因此,正确的模式是:
$httpRegex = '^\b(?:(?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%\?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$]^i';
关于PHP DomDocument 替换模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945631/