PHP preg_match_all + str_replace [英] PHP preg_match_all + str_replace
问题描述
我需要找到一种方法来替换所有的 <p>在所有<blockquote>在 <hr/> 之前.
这是一个示例 html:
2012/01/03
<blockquote><h4>文件名</h4><p>好游戏</p></blockquote><blockquote><p>Laurie Ipsumam</p></blockquote><h4>一些标题</h4><小时/><p>Lorem Ipsum</p><blockquote><p>Laurel Ipsucandescent</p></blockquote>
这是我得到的:
$pieces = purge("<hr", $theHTML, 2);$blocks = preg_match_all('/(.*?)<\/blockquote>/s', $pieces[0], $blockmatch);如果($块){$t1=$blockmatch[1];对于 ($j=0;$j<$blocks;$j++) {$paragraphs = preg_match_all('//', $t1[$j], $paragraphmatch);如果($段落){$t2=$paragraphmatch[0];对于 ($k=0;$k<$paragraphs;$k++) {$t1[$j]=str_replace($t2[$k],'<p class=\"whatever\">',$t1[$j]);}}}}
我想我真的很接近,但我不知道如何将我刚刚拼凑和修改的 html 重新组合在一起.
您可以尝试使用 simple_xml
,或者更好的 DOMDocument
(http://www.php.net/manual/en/class.domdocument.php) 之前它是一个有效的 html 代码,并使用此功能查找您要查找的节点并替换它们,为此您可以尝试 XPath
(http://w3schools.com/xpath/xpath_syntax.asp).
编辑 1:
看看这个问题的答案:
I need to find a way to replace all the <p> within all the <blockquote> before the <hr />.
Here's a sample html:
<p>2012/01/03</p>
<blockquote>
<h4>File name</h4>
<p>Good Game</p>
</blockquote>
<blockquote><p>Laurie Ipsumam</p></blockquote>
<h4>Some title</h4>
<hr />
<p>Lorem Ipsum</p>
<blockquote><p>Laurel Ipsucandescent</p></blockquote>
Here's what I got:
$pieces = explode("<hr", $theHTML, 2);
$blocks = preg_match_all('/<blockquote>(.*?)<\/blockquote>/s', $pieces[0], $blockmatch);
if ($blocks) {
$t1=$blockmatch[1];
for ($j=0;$j<$blocks;$j++) {
$paragraphs = preg_match_all('/<p>/', $t1[$j], $paragraphmatch);
if ($paragraphs) {
$t2=$paragraphmatch[0];
for ($k=0;$k<$paragraphs;$k++) {
$t1[$j]=str_replace($t2[$k],'<p class=\"whatever\">',$t1[$j]);
}
}
}
}
I think I'm really close, but I don't know how to put back together the html that I just pieced out and modified.
You could try using simple_xml
, or better DOMDocument
(http://www.php.net/manual/en/class.domdocument.php) before you make it a valid html code, and use this functionality to find the nodes you are looking for, and replace them, for this you could try XPath
(http://w3schools.com/xpath/xpath_syntax.asp).
Edit 1:
Take a look at the answer of this question:
RegEx match open tags except XHTML self-contained tags
这篇关于PHP preg_match_all + str_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!