PHP preg_replace:以下代码到底做了什么?

时间:2011-08-09 23:35:23

标签: php regex mybb

我正在修改MyBB的源代码。

以下代码来自class_feedgeneration.php

/**
 * Sanitize content suitable for RSS feeds.
 *
 * @param  string The string we wish to sanitize.
 * @return string The cleaned string.
 */
function sanitize_content($content)
{
    $content = preg_replace("#&[^\s]([^\#])(?![a-z1-4]{1,10};)#i", "&$1", $content);
    $content = str_replace("]]>", "]]]]><![CDATA[>", $content);

    return $content;
}

第一个:

$content = preg_replace("#&[^\s]([^\#])(?![a-z1-4]{1,10};)#i", "&#x26;$1", $content);

它究竟做了什么?我知道一点正则表达式,但这个有点太复杂了。

有人可以向我解释一下吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

"#& -- the char & as is
[^\s] -- one not space character (also \S could be used instead)
([^\#]) -- one not-dash character
(?![a-z1-4]{1,10};) -- and negative lookahead assertion that previous chars
                    -- are not followed by chars in a-z1-4 range
                    -- (only 1 to 10 in a row) with ; after
#i" -- case insensitive

在所有匹配中,我们选择([^\#]),将其添加到&#x26;并替换。

它用于用&xxx替换所有&#x26;xxx序列,这​​是在rss feed项中编写ampersand-char的安全方法。