【问题标题】:PHP regular expression helpPHP正则表达式帮助
【发布时间】:2011-03-30 01:50:13
【问题描述】:

我正在使用 preg_replace 去除 <p> 标签和 <li> 标签并让它们回车。我的字符串中有一些 <a> 标签,我想去掉这些标签,但保留 href 属性。例如,如果我有: <a href = "http://www.example.com">Click Here</a>,我要的是:http://www.example.com点击这里

这是我目前所拥有的

$text .= preg_replace(array("/<p[^>]*>/iU","/<\/p[^>]*>/iU","/<ul[^>]*>/iU","/<\/ul[^>]*>/iU","/<li[^>]*>/iU","/<\/li[^>]*>/iU"), array("","\r\n\r\n","","\r\n\r\n","","\r\n"), $content);

谢谢

【问题讨论】:

  • 如果您改用 HTML 解析器,您的生活可能会轻松得多。

标签: php html regex tags


【解决方案1】:

如果我是你,我会使用SimpleHTMLDom。这是文档中的一个使用示例:

// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$html->find('div', 1)->class = 'bar';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; 
// Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

【讨论】:

    【解决方案2】:

    如果需要正则表达式解决方案,这里有一个经过测试的函数,它可以根据您的要求处理锚标记(注意以下注意事项。)正则表达式以详细模式与 cmets 一起呈现:

    function process_markup($content) {
        return preg_replace(
            array( // Regex patterns
                '%<(?:p|ul|li)[^>]*>%i',        // Open tags.
                '%<\/(?:p|ul|li)[^>]*>\s*%i',   // Close tags.
                '% # Match A element (with no "<>" in attributes!)
                <a\b         # Start tag name.
                [^>]+?       # anything up to HREF attribute.
                href\s*=\s*  # HREF attribute name and "="
                (["\']?)     # $1: Optional quote delimiter
                ([^>\s]+)    # $2: HREF attribute value.
                (?(1)\1)     # If open quote, match close quote.
                [^>]*>       # Remainder of start tag
                (.*?)        # $3: A element contents.
                </a\s*>      # A element end tag.
                %ix'
            ),
            array( // Replacement strings
                "",          # Simply strip P, UL, and LI open tags.
                "\r\n",      # Replace close tags with line endings.
                "$2 $3"      # Keep A element HREF value and contents.
            ), $content);
    }
    

    我也冒昧地修改了其他正则表达式。根据需要进行调整。

    注意事项: 此正则表达式解决方案假定:所有APULLI 元素的属性中都没有尖括号&lt;&gt;。在任何CDATA 部分(例如SCRIPTSTYLE 元素、HTML cmets 或其他开始标记属性内)中没有APULLI 元素开始或结束标记.否则,这对于很多 HTML 标记应该很有效。

    我意识到很多人在听到这些词时都会畏缩:HTMLREGEX 同时说,但在这种特殊情况下,我认为正则表达式解决方案会很好用(在上述限制范围内)。 A 标签是非嵌套标签之一,因此正则表达式可以轻松匹配开始标签、内容和结束标签。当独立考虑时,其他元素的单独开始和结束标记(可以嵌套)也是如此。

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多