2014-09-19 39 views
0

我想在兩個字符串上使用PHP preg_replace函數,但我不確定要使用的正則表達式。BBCode引用標記Preg_replace模式

對於第一串,我只要求筆者值(所以一切author=後,但沒有在空格後):

[quote author=username link=1150111054/0#7 date=1150151926] 

結果:

[quote=username] 

對於第二字符串,沒有author=標籤。用戶名只是一個封閉的公開報價

[quote] username link=1142890417/0#43 date=1156429613] 

理想後出現,其結果應該是:

[quote=username] 

回答

1

使字符串author=]爲可選,以對兩種類型的字符串進行替換。

正則表達式:

^\[(\S+?)\]?\s+(?:author=)?(\S+).*$ 

如果你想提串quote上那麼你的正則表達式使用,

^\[(quote)\]?\s+(?:author=)?(\S+).*$ 

替換字符串:

[$1=$2] 

DEMO

<?php 
$string =<<<EOT 
[quote author=username link=1150111054/0#7 date=1150151926] 
[quote] username link=1142890417/0#43 date=1156429613] 
EOT; 
echo preg_replace("~^\[(\S+?)\]?\s+(?:author=)?(\S+).*$~m", "[$1=$2]", $string); 
?> 

輸出:

[quote=username] 
[quote=username] 
+0

這個工作很好,謝謝。我用第二個表達式使它不那麼貪婪。是否可以擴展表達式以從以下消除'pid = 123456':'[quote = username pid = 123456]'? – ButtressCoral 2014-09-20 16:45:10

+1

請參閱http://regex101.com/r/lH2fW8/5 – 2014-09-20 18:25:40

+0

如果使用相同的行字符串,我無法使其工作。我試圖讓它捕捉到最後的方括號。例如:http://regex101.com/r/zL4jY2/2 – ButtressCoral 2014-09-20 22:10:25

1

對於第一種:/author=(.*?) /

而對於第二個/\[quote\] (.*?) /

在你的情況下:

$str1 = "[quote author=username link=1150111054/0#7 date=1150151926]"; 
$str2 = "[quote] username link=1142890417/0#43 date=1156429613]"; 
$regex1 = '/author=(.*?) /'; 
$regex2 = '/\[quote\] (.*?) /'; 
if (preg_match($regex1, $str1, $match1)) 
    echo '[quote='.$newStr1 = $match1[1].']'; 
if (preg_match($regex2, $str2, $match2)) 
    echo '[quote='.$newStr2 = $match2[1].']'; 
0

這裏是另一種方式與一個正則表達式來處理兩者。

# Find:  '~(?|\[quote\]\s*(\S+).*|\[quote\s+author=\s*(\S+).*)~' 
# Replace: '[author=$1]' 

(?| 
     \[quote\] \s* 
     (\S+) 
     .* 
    | 
     \[quote \s+ author= \s* 
     (\S+) 
     .* 
) 

輸入:

[quote author=username link=1150111054/0#7 date=1150151926] 
[quote] username link=1142890417/0#43 date=1156429613] 

輸出:

[author=username] 
[author=username]