我目前使用这个:
$text = preg_replace('/' . $line . '/', '[x]''0[/x]', $text);
$line
是一个简单正则表达式:
https?://(?:.+?'.)?dailymotion'.com/video/[A-Za-z0-9]+
到目前为止工作正常。但有两件事我需要,我不知道怎么做:
…我不想执行替换,如果该字符串包含在BBCode
中,即
[bla] http://www.dailymotion.com/video/xuams9 [/bla]
或
[bla = http://www.dailymotion.com/video/xuams9] trololo [/bla]
或
[bla = ' http://www.dailymotion.com/video/xuams9 '] http://www.dailymotion.com/video/xuams9 [/bla]
第二件事是,我只想匹配到第一个空格。这是我目前使用的:
$text = preg_replace('/' . $line . '(?:[^ ]+)?/', '[x]''0[/x]', $text);
我不知道,我应该这样做还是有更好的方法。
所以,基本上我只是尝试匹配
http://www.dailymotion.com/video/test4从这个:
[tagx='http://www.dailymotion.com/video/test1']http://www.dailymotion.com/video/test2[/tagx] | [tagy]Hello http://www.dailymotion.com/video/test3 World[/tagy] | [tagz]Hello World[/tagz] http://www.dailymotion.com/video/test4
这是我到目前为止所做的(稍微有效):
(?:(?<!('['/url']|'['/url=))('s|^))' . $line . '(?:[^ ]+)(?:(?<![[:punct:]])('s|'.?$))?
您可以使用隐藏断言来做到这一点。http://php.net/manual/en/regexp.reference.assertions.php
通过在$line
之前使用下面的后面代码 (?<!'[bla]|'[bla=|'[bla=')
它将匹配不以[bla]
, [bla=
和[bla='
开头的$link
→试试这个:
$text = array();
$text[ 0 ] = "[bla]http://www.dailymotion.com/video/xuams9[/bla]";
$text[ 1 ] = "[bla=http://www.dailymotion.com/video/xuams9]trololo[/bla]";
$text[ 2 ] = "http://www.dailymotion.com/video/xuams9";
$text[ 3 ] = "A http://www.dailymotion.com/video/xuams9 B C";
$line = "/http:'/'/www.dailymotion'.com'/video'/[A-Za-z0-9]+/";
$tag = array();
$tag[ 0 ] = "/'[[A-Za-z]{1,12}']http:'/'/www.dailymotion'.com'/video'/[A-Za-z0-9]+'['/[A-Za-z]{1,12}']/";
$tag[ 1 ] = "/'[[A-Za-z]{1,12}=http:'/'/www.dailymotion'.com'/video'/[A-Za-z0-9]+'][A-Za-z0-9]{0,}'['/[A-Za-z]{1,12}']/";
foreach( $text as $k=>$v ) {
if( preg_match( $tag[ 0 ], $v ) == false && preg_match( $tag[ 1 ], $v ) == false ) {
echo '!';
$output = preg_replace( $line, '[x]''0[/x]', $v );
}
else { $output = $v; };
echo "Text #" . ( $k + 1 ) . ": {$output}<br />";
}
结果:Text #1: [bla]http://www.dailymotion.com/video/xuams9[/bla]
Text #2: [bla=http://www.dailymotion.com/video/xuams9]trololo[/bla]
!Text #3: [x]http://www.dailymotion.com/video/xuams9[/x]
!Text #4: A [x]http://www.dailymotion.com/video/xuams9[/x] B C