Php preg_replace()使用

时间:2014-11-05 13:02:38

标签: php string replace preg-replace

我正在尝试更改字符串的某些部分。我使用preg_replace()函数进行此stuation但我无法成功。

这是一个例子。

$str = "Suspendisse rutrum rhoncus leo vitae vehicula. <span class="sdsad"> Nunc nec dapibus nisi.</span> Donec facilisis mauris sapien, eget blandit enim  dignissim auctor. <span style="text-decoration: underline;" class="sadsad">Nullam a porta orci.</span>";

我需要以"<span"开头,然后直到">" charecter并将其转换为<p>或其他内容。

$str = preg_replace('/<span.*>/', '<p>', $str);

我试图像这样解决这个问题,但它会返回相同的值。

我需要做什么?

谢谢..

2 个答案:

答案 0 :(得分:1)

这个正则表达式将为您解决问题。

$str = 'Suspendisse rutrum rhoncus leo </span> vitae vehicula. <span class="sdsad"> Nunc nec dapibus nisi.</span> Donec facilisis mauris sapien, eget blandit enim  dignissim auctor. <span style="text-decoration: underline;" class="sadsad">Nullam a porta orci.</span>';
$str_replaced = preg_replace('/<(\/{0,1})span[^>]*>/','<$1p>',$str);
echo $str_replaced;

它可以选择将尾部斜杠放入标签中,这样您只需要一次调用。

答案 1 :(得分:0)

您忘记了此处的抓取组()

$str = preg_replace('/<span(.*)>/', '<p>', $str);

更多信息: http://www.regular-expressions.info/brackets.html