我需要一个php正则表达式来替换一个标签 [英] I need a php regular expression that replaces one tag with another

查看:137
本文介绍了我需要一个php正则表达式来替换一个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要匹配以下标记:

pre> < SPAN style =TEXT-DECORATION:underline> text sample< / SPAN>

我需要用html3兼容标记替换span,但保留文本。更换后的最终标签应该如下所示:

 < u>文本样本< / u> 

我对正则表达式不太满意,似乎无法得出答案。



预先感谢您。

解决方案

正则表达式不是为标签操作而设计的。



如果您有任何形式的嵌套,它会变得混乱。 $ b

然而,考虑到非常简单的例子,您可以这样做:

  $ MyString = preg_replace 
('/(?si)<SPAN\s+style\s*=\s*\"TEXT-DECORATION:\s*underline;?\"\s*>(.*?)< ; \ / SPAN> /'
,'< u> $ 1'
,$ MyString
);





但是这在许多方面都存在缺陷,而且你更好请使用专为操作代码而设计的工具。



查看 DOMDocument-> loadHTML()相关功能


Here is what I need to be able to do:

I need to match the following tag:

<SPAN style="TEXT-DECORATION: underline">text sample</SPAN>

I need to replace the span with an html3 compliant tag, but keep the text in between. The final tag should look like this after replacement:

<u>text sample</u>

I'm just not good with regular expressions and can't seem to come up with the answer.

Thank you in advance.

解决方案

Regular expressions are not designed for tag manipulation.

If you have any form of nesting going on, it gets messy.

However, given the very simple example provided you could perhaps do this:

$MyString = preg_replace
    ( '/(?si)<SPAN\s+style\s*=\s*"TEXT-DECORATION:\s*underline;?"\s*>(.*?)<\/SPAN>/'
    , '<u>$1</u>'
    , $MyString
    );


But this is flawed in many ways, and you are much better off using a tool designed for manipulating tags instead.

Have a look at DOMDocument->loadHTML() and related functions.

这篇关于我需要一个php正则表达式来替换一个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆