【问题标题】:PHP DomDocument to replace patternPHP DomDocument 替换模式
【发布时间】:2012-10-18 00:57:57
【问题描述】:

我需要查找和替换指向超链接的 http 链接。这些 http 链接在 span 标签内。

$text 有 html 页面。其中一个跨度标签有类似

<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>

显然上面的代码不适用于这种情况。有没有一种方法可以在不使用 preg_replace 的情况下使用 DOMDocument 搜索和替换模式?

更新:回答 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() 有什么问题?
  • 菲尔,我更新了问题。谢谢。
  • 您的正则表达式没有被转义。您必须转义转义字符和分隔符!

标签: php search replace pattern-matching domdocument


【解决方案1】:

正则表达式非常适合这个问题 - 所以最好使用preg_replace

现在您的模式中只有几个未转义的delimiters,因此请转义它们或选择另一个字符作为分隔符 - 例如,^。因此,正确的模式是:

$httpRegex = '^\b(?:(?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%\?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$]^i';

【讨论】:

  • 谢谢尼基塔!它有助于。当我做 preg_replace($httpRegex, "$0", $text);它给了我一个没有“http”的链接。我可以用 preg_replace($httpRegex, "http://$0", $text); 替换代码但是,如果文本中的链接是codesomethingcode,它会给我codehttp:/code。我可以有 codewww.link.comcodecodelink.com</span>code 之类的链接。我是否需要编写两个正则表达式来解决这个问题?再次感谢。
  • 我会使用 preg_replace_callback 函数 - 这是一个示例:pastebin.com/GfPjtbku
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2016-01-27
相关资源
最近更新 更多