如何直接在<p>
标签内的html内容中找到hello
关键字(不是子标签,例如<a>
标签),并将其替换为链接
我不想改变html属性
HTML:<p>hello world
<a href="hello.html">hello</a>
</p>
<img src="hello.png" alt="image" />
我需要这样的输出:
<p><a href="hello">hello</a> world
<a href="hello.html">hello</a>
</p>
<img src="hello.png" alt="image" />
不是这样的:
<p><a href="hello">hello</a> world
<a href="<a href="hello">hello</a>.html">hello</a>
</p>
<img src="<a href="hello">hello</a>.png" alt="image" />
What i tried
include('inc/simple_html_dom.php');
// Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$dom = '
<p>hello world
<a href="hello.html">hello</a>
</p>
<img src="hello.png" alt="image" />
';
$html->load($dom);
foreach($html->find('p') as $p)
{
$p->innertext = str_replace($searchArray, $replaceArray, $p->innertext);
}
echo $html;
你应该能够做到:
foreach($html->find('text') as $text){
if($text->parent->tag != 'p') continue;
$text->outertext = str_replace($searchArray, $replaceArray, $text->outertext);
}
在这种情况下,如果您设置
$searchArray = 'hello '; // with a blank space after hello
它应该像你希望的那样工作