开发者

php preg_replace need help

I have created a function to search through strings and replace keywords in those strings with links. I am using

preg_replace('/\b(?<!=")(?<!=\')(?<!=)(?<!=&quot;)(?<!>)(?<!&gt;)' . $keyword . '(?!</a)(?!&lt;/a)\b', $newString, $row);

which is working as expected. The only issue is that if someone had a link like this

<a href="www.domain.tdl/keyword.html">Luxury Automobile sales</a>

Automobile being our $keyword in this example.

It would end up looking like

<a href="www.domain.tdl/keyword.html">Lux开发者_开发百科ury <a href="www.domain.tdl/keywords.html">Automobile</a> Sales</a>

You can understand my frustration. Not being confident in regex I thought I would ask if anyone here would know a solution.

Thanks!


How about a proper HTML parser like DOMDocument?

$html = '<a href="www.domain.tdl/keyword.html">Luxury Automobile sales</a>';
$dom  = new DomDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('a');
foreach ($nodes as $node)
{
  $node->nodeValue = str_replace('Automobile', 'Cars', $node->nodeValue);
  echo simplexml_import_dom($node)->asXML();
}

Is not a problem to get element attribute too

foreach ($nodes as $node)
{
  $attr = $node->getAttributeNode('href');
  $attr->value = str_replace('Automobile', 'keyword', $attr->value);
  echo simplexml_import_dom($node)->asXML();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜