Jack
Jack

Reputation: 185

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">Luxury <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!

Upvotes: 0

Views: 232

Answers (1)

ajreal
ajreal

Reputation: 47321

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();
}

Upvotes: 3

Related Questions