开发者

Find a string not surrounded by a BBcode using Regex

I am in need of a regular expression that will find, and replace, a word/phrase in a string only if it's not in a开发者_如何转开发n [url] BBcode.

$string = "Word [url='http://domain.com']Word test[/url]";

The regex should not do anything with "Word test", only the first occurrence of "Word".

EDIT: To be more specific, this is an addon for a forum software that monitors the messages for mentions of artists. If one occur, the artist's name is replaced with an URL to a thread about that artist, unless it's not already part of an URL (either in the link itself or the desc). After a second thought, it shouldn't be triggered if it's used in any tags that isn't pure markup (b,i,u,color,lists, etc). So an easy way to define what tags can be in to be replaced would be brilliant!

Thanks in advance!


$inputStr = "Coldplay [URL='localhost/threads/coldplay-paradise.32/']Coldplay - \"Paradise\"[/URL] Coldplay";

function replace( $matches ) {
    if( isset( $matches[2] ) && $matches[2] )
        return "[url='coldplay']".$matches[2]."[/url]";
    return $matches[0];
}

$regex = '/(\[.*?\].*?\[\/.*?\])?(Coldplay)?(.+?)?/si';
$outputStr = preg_replace_callback( $regex, 'replace', $inputStr );
echo $outputStr;

result:

[url='coldplay']Coldplay[/url][URL='localhost/threads/coldplay-paradise.32/']Coldplay - "Paradise"[/URL] [url='coldplay']Coldplay[/url]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜