php 什么是 preg_replace 正则表达式来替换这个 HTML 标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20978386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the preg_replace regex to replace this HTML tag?
提问by Dannyboy
How would I convert strings like this:
我将如何转换这样的字符串:
<span class="it">CONTENT</span>
Into this:
进入这个:
{it}CONTENT{/it}
While keeping CONTENT intact?
同时保持内容完整?
回答by Mave
preg_replace('/<span class="it">(.*?)<\/span>/', '{it}{/it}', $text)
This is not the most versatile solution, but this works for your code. There is the possibility to have the content of the class attribute as a variable as well, but that won't be too hard to figure out now.
这不是最通用的解决方案,但这适用于您的代码。也有可能将 class 属性的内容作为变量,但现在不难弄清楚。
回答by Dmitriy.Net
Try this
尝试这个
preg_replace('/<span.+class="(.+)">(.+)<\/span>/', '{}{/}', $text);
回答by Amal Murali
The following should get you started:
以下应该让你开始:
preg_replace('#<span\s*class="(\w*)">(\w*)</span>#i', '{}{/}', $str);
Output:
输出:
{it}CONTENT{/it}

