3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $desc = '<p> <strong>Nappe bouton power</strong><br> <u class="uuu"><i title="a bouton power b">Nappe bouton power, compatible Samsung Galaxy S6 Edge G925F.</i></u> </p>'; echo canLinkThisWordIn('bouton power', $desc, true); function canLinkThisWordIn($word, $html, $linkIt){ $forbidenTagsArray = array('strong', 'a', 'b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'); $dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXpath($dom); $wordTags = $xpath->query("//*[text()[contains(translate(., '".strtoupper($word)."', '".strtolower($word)."'), '".strtolower($word)."')]]"); foreach($wordTags as $wordTag){ if(checkTagAndParent($wordTag, $forbidenTagsArray)){ if($linkIt){ //$newWordTagValue = ''; //$wordTag->nodeValue = ''; //$wordTag->appendChild($dom->createTextNode($titleText)); //$replacement = $dom->createDocumentFragment(); //$replacement->appendChild($newWordTag); $sensitiveWord = $word; $newWordTagLink = '<a href="#" title="#" class="internalink"><b>'.$sensitiveWord.'</b></a>'; $newWordTagHtml = str_ireplace($sensitiveWord, $newWordTagLink, getNodeInnerHTML($wordTag)); $helper = new DOMDocument(); $helper->loadHTML($newWordTagHtml); $newWordTag = $dom->createElement('b'); $newWordTag->appendChild($dom->importNode($helper->documentElement, true)); // save to dom $wordTag->parentNode->replaceChild($newWordTag, $wordTag); $body = $dom->getElementsByTagName('body'); $body = $body->item(0); $newHTML = $dom->saveHTML($body); return $newHTML; $newHTML = $dom->saveHTML(); $newHTML = str_ireplace(array('<html>', '</html>', '<body><p>', '</p></body>'), '', $newHTML); return '<p>'.$newHTML.'</p>'; } return true; } } return false; } function checkTagAndParent($tag, $forbiden){ if(!in_array($tag->tagName, $forbiden)){ if($tag->parentNode){ $parentTags = array_filter(explode("/", preg_replace("/\[[^]]+\]/", "", $tag->getNodePath()))); foreach($parentTags as $parentTag){ if(in_array($parentTag, $forbiden)){ return false; } } } return true; } return false; } function getNodeInnerHTML(DOMNode $element){ $innerHTML = ""; $children = $element->childNodes; foreach($children as $child){ $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; } function getNodeOuterHTML($e){ $doc = new DOMDocument(); $doc->appendChild($doc->importNode($e, true)); return $doc->saveHTML(); }
based on 9DviX
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.2.6
<body><p> <strong>Nappe bouton power</strong><br><u class="uuu"><b><html><body><p>Nappe <a href="#" title="#" class="internalink"><b>bouton power</b></a>, compatible Samsung Galaxy S6 Edge G925F.</p></body></html></b></u> </p></body>