【问题标题】:preg_replace regular expression change particular symbols inside tagpreg_replace 正则表达式更改标签内的特定符号
【发布时间】:2011-07-15 15:09:42
【问题描述】:

我有一个 span 元素和其中的一些文本。 有时这个元素的内容也包括其他元素(标签)。

例如:

<span id="span_id"><a href="http://someurl" title="sometitle">value</a></span>

我需要做的是将 span 中的所有“”转换为“~gt~”。 可能有层次结构,例如a 元素内可能有 img 标签等。

所以如果输入是:

<span id="span_id"><a href="http://someurl" title="sometitle"><img src="http://anotherurl"/></a></span>

输出应该是:

<span id="span_id">~lt~a href="http://someurl" title="sometitle"~gt~~lt~img src="http://anotherurl"/~gt~~lt~/a~gt~</span>

谢谢!

UPD 我已经从这里PHP: using preg_replace with htmlentities

【问题讨论】:

  • 如果span 中有span 怎么办?例如,&lt;span id="span_id"&gt;&lt;a href=""&gt;some text is &lt;span style="color: green;"&gt;GREEN&lt;/span&gt;!&lt;/a&gt;&lt;/span&gt; 我猜你想要span#span_id 里面的所有东西,即使它是另一个span。对?在这种情况下,HTML 解析器 + str_replace() 可能是个好主意。
  • 嗯,实际上 span 中没有 span,我可以假设它是一个前提。使用 HTML 解析器的问题在于 SPAN 内部 - 并不总是有正确的 HTML,因此例如它可能会打开 A 标记而不关闭它。这就是为什么我决定用正则表达式预处理文本。然后解析它,做一些事情,然后将值替换回来。

标签: regex preg-replace


【解决方案1】:

正如其他人所说,您需要接受您提出的问题的答案。

这是一个使用preg_replace_callback() 函数的解决方案。主正则表达式匹配“最里面”的 SPAN 元素(但请参阅:下面的 CAVEAT)。回调函数处理元素内容,将每个&amp;lt;替换为&amp;lt;,将每个&amp;gt;替换为&amp;gt;

function escapeSpanContents($text) {
    return preg_replace_callback('%
        # Match an innermost SPAN element.
        (<span\b[^>]*>)   # $1: SPAN element start tag.
        (                 # $2: SPAN element contents.
          [^<]*           # Non-start or end tag < chars. {normal*}
          (?:             # Begin {(special normal*)*} construct.
            <             # {special} is any < that is...
            (?!/?span\b)  # neither a <span or </span
            [^<]*         # More {normal*}
          )*              # Finish "Unrolling-the-Loop"
        )                 # End $2: SPAN element contents.
        (</span\s*>)      # $3: SPAN element end tag.
        %sx', '_escapeSpanContentsCallback', $text);
}
function _escapeSpanContentsCallback($matches) {
    $matches[2] = str_replace(
        array('<', '>'),
        array('&lt;', '&gt;'),
        $matches[2]);
    return $matches[1] . $matches[2] . $matches[3];
}

CAVEATS:这将无法匹配具有包含尖括号的开始标记属性的 SPAN 元素(应该很少见)。它还会错误地匹配出现在 COMMENT、SCRIPT 和 STYLE 元素中的 SPAN“元素”。尽管此解决方案会做得相当不错,但如果您需要 100% 可靠的结果,最好使用 HTML 解析器。

【讨论】:

  • 感谢您的信息,我实际使用过:$html = preg_replace_callback('@\&lt;span(.*?)\&gt;(.*?)\&lt;\/span\&gt;@mis','_handle_match', $html); function _handle_match($match) { return '&lt;span'.$match[1].'&gt;' . str_replace(array('&lt;','&gt;','"'),array('&amp;lt;', '&amp;gt;', '&amp;quot;'), $match[2]) . '&lt;/span&gt;';
猜你喜欢
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2014-05-13
  • 1970-01-01
  • 2017-07-02
  • 2012-06-26
  • 1970-01-01
相关资源
最近更新 更多