1

所以我想用字符串替换“字符串”,<a>"strings"</a>用字符串替换另一个数组。起初一切都像魅力一样,它取代了第一个巧合而不是标签 > < ,但是当我开始用字符串和 url 填充数组时,我发现如果它取代了 "Fantasy games" -><a href="ASDFASDF">Fantasy games</a>然后它必须取代 " Fantasy”,它只是跳过正则表达式的 >string< 检查并继续并替换它,破坏 html 代码并创建解析错误。

所以我假设我做错了什么或缺少参数或其他东西,因为如果内容有 >string< 它不会替换它但是如果我用 preg_replace 做它就像我做错了因为当它要替换数组的下一个元素时,它不会像 >string< 那样检测到它。

这是代码:

// DB content
// $Keywords=array("Fantasy games", "Fantasy");
// $URL=array("http://www.whatever.com", "http://www.whatever2.com");

$i=0;
// Insert the links and returns the processed content.
foreach ($SQLResult as $row){
    $Keywords[$i]="/[^>](".$row->Keyword.")[^<]/i";
    $URLS[$i]=' <a href="'.$row->URL.'">$1</a> ';
    $i++;
}   
$Content=preg_replace($Keywords, $URLS, $Content, 1);
4

1 回答 1

0

正如@Jens 所指出的,我从在这个问题上找到的代码开始:https ://stackoverflow.com/posts/4209925/edit

<?php

$dom = new DOMDocument();
// loadXml needs properly formatted documents, so it's better to use loadHtml, but it needs a hack to properly handle UTF-8 encoding
$dom->loadHtml(mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8"));

$xpath = new DOMXPath($dom);

foreach($xpath->query('//text()[not(ancestor::a)]') as $node)
{
    $i=0; 
    // Insert the links and returns the processed content.
    foreach ($SQLResult as $row){
        $replaced = str_ireplace($row->Keyword, '<a href="'.$row->URL.'">$0</a>', $node->wholeText);
        $newNode  = $dom->createDocumentFragment();
        $newNode->appendXML($replaced);
        $node->parentNode->replaceChild($newNode, $node);
    }
}

// get only the body tag with its contents, then trim the body tag itself to get only the original content
echo mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
于 2013-07-22T12:32:50.750 回答