1

由于某些原因,我得到了以下不正确嵌套的 BBcode

[url=]你好[url=]世界[/url][/url]

我只想删除嵌套的 url 标签。结果应该是:[url=] Hello world [/url]

我有一篇很长的文章,这种情况发生了很多次。对此有什么建议吗?


如何删除嵌套标签在一篇这样的文章中发生了很多次

[url=] 你好 [url=] 世界 [/url][/url] [url=] 你好 [url=] 世界 [/url][/url] [url=] 你好 [url=] 世界 [/url] [/网址]

谢谢!

4

2 回答 2

1

以下经过测试的脚本应该可以解决问题。它使用递归正则表达式和preg_replace_callback(). 它将处理任何嵌套级别的 URL 标签,并去除除最外层标签之外的所有标签:

<?php // test.php 20110325_1500
$re_url = '%# Match outermost [URL=...]...[/URL] (may have nested URL tags
    (\[URL\b[^[\]]*+\])       # $1: opening URL tag.
    (                         # $2: Contents of URL tag.
      (?:                     # Group of contents alternatives.
        (?:(?!\[/?URL\b).)++  # One or more non-"[URL", non-"[/URL"
      | (?R)                  # Or recursively match nested [URL]..[/URL].
      )*+                     # Zero or more contents alternatives.
    )                         # End $2: Contents of URL tag.
    (\[/URL\s*+\])            # $3: Outermost closing [/URL]
    %six';
function strip_nested_url_tags($text) {
    global $re_url;
    $return = '_handle_url_callback';
    return preg_replace_callback($re_url, $return, $text);
}
function _handle_url_callback($matches) {
    global $re_url;
    static $depth = 0;
    $depth++;
    $return = '_handle_url_callback';
    $matches[2] = preg_replace_callback($re_url, $return, $matches[2]);
    if ($matches[2] === NULL)
    { // On error, preg_replace_callback returns NULL.
        exit('Error - Message is too long or too complex.');
    }
    if (--$depth > 0) return $matches[2];
    return $matches[1] . $matches[2] . $matches[3];
}
$data = file_get_contents('testdata.html');
$data = strip_nested_url_tags($data);
file_put_contents('testdata_out.html', $data);
?>
于 2011-03-25T22:30:42.583 回答
0

这可能有效:

$string = preg_replace("/(\[url=[^\]]*\].*)\[url=[^\]]*\](.*)\[\/url\](.*\[\/url\])/is", "$1$2$3", $string);

但是,您应该找到问题的根源,而不是试图撤消它。

于 2011-03-25T21:11:43.337 回答