簡體   English   中英

關於正則表達式的兩個問題

[英]Two questions regarding regular expressions

我目前使用這個:

$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/zh/regexp.reference.assertions.php

通過在$ line之前使用以下lookback

(?<!\\[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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM