简体   繁体   English

PHP - 解析 HTML,选择标签,在所选标签内插入另一个 HTML 字符串

[英]PHP - Parse HTML, Select tag, Insert another HTML string inside selected tag

I am trying to insert HTML string inside another HTML element parsed in created DOM with loaded HTML from string;我正在尝试将 HTML 字符串插入到在创建的 DOM 中解析的另一个 HTML 元素中,其中包含从字符串加载的 HTML;

Here is my code:这是我的代码:

PHP: PHP:

$str = $attributes["description_text"]; // HTML string
$dom = new DOMDocument; // initialize the domdocument
$dom->loadHTML($str); // load our html into the $dom object
$items = $dom->getElementsByTagName('mark'); // retrieving elements by tag

$gear = $dom->createElement('a', "Lorem ipsum dolor sit amet");
$dom->appendChild($gear);
    
$output_dom = $dom->saveHTML();

return '<p>'. $output_dom .'</p>';

HTML ($str content): HTML($str 内容):

Phasellus eu arcu vestibulum, ultrices massa eu, <mark>TOOLTIP</mark> sodales dui.

Desired Result ( a tag inside mark tag):期望的结果( a内标签mark标签):

<p>Phasellus eu arcu vestibulum, ultrices massa eu, <mark>TOOLTIP<a>Lorem ipsum dolor sit amet</a></mark> sodales dui.</p>

Current Output:电流输出:

<p>Phasellus eu arcu vestibulum, ultrices massa eu, <mark>TOOLTIP</mark> sodales dui.</p> 
<a>Lorem ipsum dolor sit amet</a>

So now new string appended in the end of whole paragraph, not inside mark tag所以现在新字符串附加在整个段落的末尾,而不是在mark标签内

Found a solution, selected an item(0) from elements stored in $items , and called appendChild() on it, thanks to @NigelRen找到了一个解决方案,从$items存储的元素中选择了一个item(0) ,并在其上调用了appendChild() ,感谢@NigelRen

$first_mark = $items->item(0);
$first_mark->appendChild($gear);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM