关于正则表达式的两个问题

时间:2013-06-02 03:00:33

标签: php regex

我目前使用它:

$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|\.?$))?

2 个答案:

答案 0 :(得分:0)

您可以使用lookbehind断言来执行此操作。 http://php.net/manual/en/regexp.reference.assertions.php

在$ line

之前使用以下lookbehind

(?<!\[bla]|\[bla=|\[bla=')

它将匹配不是以[bla][bla=[bla='开头的$ link。

答案 1 :(得分:0)

试试这个:

$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