开发者

How to remove improper nesting BBcode tags using PHP

开发者 https://www.devze.com 2023-02-20 01:36 出处:网络
For some reasons I got the following improperly nested BBcode [url=] Hello [url=] world [/url][/url] I just want to remove the nested url tags. The result should be:

For some reasons I got the following improperly nested BBcode

[url=] Hello [url=] world [/url][/url]

I just want to remove the nested url tags. The result should be: [url=] Hello world [开发者_JS百科/url]

I have a very long article and this happens many times. Any suggestions for this?


How to remove the nested tags happened many times in one article like this

[url=] Hello [url=] world [/url][/url] [url=] Hello [url=] world [/url][/url] [url=] Hello [url=] world [/url][/url]

Thanks!


The following tested script should do the trick. It uses a recursive regex and a recursive application of preg_replace_callback(). It will handle URL tags to any nested level and strips all but the outermost tags:

<?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);
?>


This might work:

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

You should find the root of the problem rather than trying to undo it, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消