以下经过测试的脚本应该可以解决问题。它使用递归正则表达式和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);
?>