Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

php - Adding abbr tags via DOMDocument to create a tooltip

I want to search for some string in a given HTML and want to replace them to make a tooltip - like:

<div>
  <p>This is BMW 3 in red.</div>
</div>
<div>
  <p>This is BMW<abbr>BMW is a car manufacturer</span> 3 in red.</div>
</div>

What I already have is a function to search and replace strings anywhere in the DOM (even if there is a deep structure) that works pretty fine so far:

protected function domTextReplace(string $search, string $replace, DOMNode $domNode)
{
    if ($domNode->hasChildNodes()) {
        $children = [];
        foreach ($domNode->childNodes as $child) {
            $children[] = $child;
        }
        foreach ($children as $child) {
            if ($child->nodeType === XML_TEXT_NODE) {
                $newText = str_replace($search, $replace, $child->wholeText);
                $newTextNode = $domNode->ownerDocument->createTextNode($newText);
                $domNode->replaceChild($newTextNode, $child);
            } else {
                $this->domTextReplace($search, $replace, $child);
            }
        }
    }
}

Problem here is, that I don't want to create a simple text node in the p-tag but a text node interrupted with a tag inside. Any idea how to solve this?

question from:https://stackoverflow.com/questions/66050139/adding-abbr-tags-via-domdocument-to-create-a-tooltip

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...