- preg_replace: documentation ( source)
<?php
$html = <<<HTML
<a class="dessert" href="http://mywebsite.com/chocolate.php" title="Try out our new chocolate">chocolate</a>
<a class="dessert" href="http://mywebsite.com/chocolate.php" title="Try out our new chocolate cookies">chocolate</a>
<a class="dessert" href="http://mywebsite.com/chocolate.php" title="Try out our new chocolate vanilla cookies">chocolate</a>
HTML;
$doc = new DomDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendXML($html);
$doc->appendChild($fragment);
$nodes = $doc->getElementsByTagName('a');
foreach ($nodes as $node) {
$node->setAttribute(
"title",
preg_replace("~\bchocolate(?:(?:\hvanilla)?\hcookies)?\b~", "chocolate chip cookies", $node->getAttribute("title")
)
);
}
echo $doc->saveHTML();