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(?<!=")(?<!=\')(?<!=)(?<!=")(?<!>)(?<!>)' . $keyword . '(?!</a)(?!</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();
}
精彩评论