【问题标题】:How to strip <a> tags in an xml file?如何去除 xml 文件中的 <a> 标签?
【发布时间】:2015-01-05 06:46:48
【问题描述】:

我在一个 xml 文件中有一个 &lt;a&gt; 标记。我只想去除&lt;a&gt; 标签。

例如:

<test>This is a line with <a name="idp173968"></a> tags in it</test>

我不能用str_replace替换标签,因为&lt;a&gt;标签属性是多种多样的。

我试过了:

preg_replace("/<a[^>]+\>/i", "", $content);

如果标签的结构像这样&lt;a name="idp173968"/&gt;,它工作正常。

那么,在我的情况下如何去除标签?

预期输出:

<test>This is a line with tags in it</test>

【问题讨论】:

标签: php html regex xml preg-replace


【解决方案1】:

您可以尝试一个非常简单的正则表达式,例如

<a\s.*?<\/a>

Regex Demo

示例

echo preg_replace("/<a\s.*?<\/a>/i", "", $content);
=> <test>This is a line with  tags in it</test>

$content="<test>This is a line with <a name=\"idp173968\"></a> tags in it</test><article-meta>asdf</article-meta>";
echo preg_replace("/<a\s.*?<\/a>/i", "", $content);
=><test>This is a line with  tags in it</test><article-meta>asdf</article-meta>

【讨论】:

  • 我的 xml 文件中有 &lt;article-meta&gt; 标签。因为这个标签在开头和结尾都有&lt;aa&gt;,所以它也替换了它。如何避免?
  • @VidhyaRaju 只需在正则表达式中添加 \s 以确保 &lt;a 之后的空间。检查编辑的答案
【解决方案2】:
<?php
$string = '<test>This is a line with <a name="idp173968"></a> tags in it</test>';
$pattern = '/<a\s.*?<\/a>/i';
echo preg_replace($pattern, "", $string);
?>

【讨论】:

    猜你喜欢
    • 2013-09-03
    • 2013-08-01
    • 2012-10-01
    • 2013-03-24
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2017-09-21
    • 2020-09-02
    相关资源
    最近更新 更多