2016-10-02 102 views
1

我怎能取代从一个字符串:如何用属性替换标签为空字符串?

"this is a <p id="1" /> text <p id="2" /> of a string" 

要:

"this is a <br> text <br> of a string" ? 

不久我想<br>替换所有<p ... />存在的字符串。

+0

str_replace将工作,或者如果你有多个p标签比使用正则表达式 – devpro

+0

我不能使用str_replace becouse属性

不是一个costant。 –

+0

现在你有几个解决方案给出下面试试 – devpro

回答

2

更新:(只<p ... />

echo preg_replace("/<p[^\/]*\/>/i", "<br />", 'this is a <p id="1" /> text <p id="2" /> of a string'); 
+0

这将增加br在结束标签 – devpro

+0

@devpro检查更新 – ADev

+0

良好的兄弟。另外chk我的解决方案:) – devpro

1

您可以沿着使用preg_replace()str_replace()

$newString = preg_replace("/<p[^>]*?>/", "", $yourString); // will remove all starting tag 
$addNewLine = str_replace("</p>", "<br />", $newString); // will replace closing tag with <br> 
0

试试:

<?php 
echo preg_replace("<p id=\"d\"/>", "<br>", "this is a <p id=\"1\" /> text <p id=\"2\" /> of a string"); 
?> 

您将获得:

this is a 

text 

of a string 
+0

关闭p标记怎么办? – devpro