PHP:str_replace如何移动html标签

时间:2014-03-27 19:30:30

标签: php regex html-parsing

我是新手,我有一些PHP str_replace的问题,我需要建议

$a = '<a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank"><p class="myclass">';

我想像这样替换html标签

在:

<a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank"><p class="myclass">

后:

<p class="myclass"><a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank">

我尝试编码,我在class =&#34; ...&#34;中遇到动态值问题。和href =&#34; ...&#34;

请建议并感谢:)

1 个答案:

答案 0 :(得分:0)

以下代码仅适用于您在问题中提供的样本:

这是使用preg_replace()而不是str_replace()

$a = '<a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank"><p class="myclass">';
$a = preg_replace("|(<a [^>]*>)(<p [^>]*>)|", "$2$1", $a);
print "$a\n";

在这里使用正则表达式我正在捕获两组$1$2中的两个标签。在替换期间,我只是交换他们的地方,如$2$1