【问题标题】:Php preg_replace() usingphp preg_replace() 使用
【发布时间】:2014-11-05 13:02:38
【问题描述】:

我正在尝试更改字符串的某些部分。我对这种情况使用了 preg_replace() 函数,但我无法成功。

这是一个例子。

$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>";

我需要以"&lt;span" 开头的零件,毕竟直到"&gt;" 字符,然后将其转为&lt;p&gt; 或其他内容。

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

我正在尝试这样解决这个问题,但它返回相同的值。

我需要做什么?

谢谢你..

【问题讨论】:

    标签: php string replace preg-replace


    【解决方案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;
    

    它会选择性地将尾部斜杠放入标签中,因此您只需要一次调用。

    【讨论】:

    • 复杂的方法?!
    • 一点也不。这样,您将一次性将 替换为

    【解决方案2】:

    你忘了这里的捕获组()

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

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

    【讨论】:

    • 不幸的是我得到了同样的结果。
    • @brk:我在infoheap.com/tool/php-preg_replace-sandbox 上进行了测试——效果很好。也许某种缓存?
    • 是的,它在该链接中正常工作。我正在努力寻找一些原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多