正则表达式用于替换任何 html 标签中的特定标签


Regex for replacing a specific tag inside any html tag

在我的一个应用程序中,我需要在所有html标签属性中去除或删除特定标签,例如:

 <div<del>class</del>=<del>"example"</del>>

我想删除所有这些从服务器端脚本生成的<del>标签。我正在使用以下preg_replace

  preg_replace("/<.*?>/", "", $string);

但它正在替换所有标签,我只想替换 html 标签中的标签。我不想删除所有<del>标签。我只想删除那些出现在 html 标签中的<del>标签。

使用正则表达式:

<[^<>]+>

其中 [^<>]+ 是匹配除 <> 之外的所有字符的否定类。

正则表达式101演示

但是,如果您的 html 标签

中没有这些标签,它也会替换 html 标签。

如果是这样,您可以尝试以下正则表达式:

(?<==|")<[^<>]+>

编辑:如果你的问题很具体,你应该在你的问题中更具体。

只需使用正则表达式来替换:

<'/?del>
你可以

这样做:

preg_replace('/(?>(?><|'G(?<!^))[^<>]++'K|'G(?<!^))<[^>]++>/', '', '<div class=<some_tag>"example"</some_tag>>');

图案详情:

(?>            # non capturing group (atomic)
    (?>
        <|'G(?<!^)   # < or a contigous match
    )
    [^<>]++'K  # common content of the good tag until a bracket ('K reset the match)
  |            # OR
    'G(?<!^)   # a contiguous match not at the start of the string
)              # close the non capturing group
<[^>]++>       # the ugly tag to remove

您可以使用此函数

strip_tags('<div<del>class</del>=<del>"example"</del>>', '<del>');

如果您使用strip_tags函数,您将获得以下输出

'<div class="example">'

祝你好运。。。