2010-03-31 91 views
1

我試圖使用正則表達式(的preg_match和preg_replace函數)執行以下操作:PHP正則表達式查找並追加到字符串

找到這樣的字符串:

{%title=append me to the title%} 

然後將解壓出來的title部分和append me to the title部分。我可以再使用執行str_replace()函數等

鑑於我在可怕的正則表達式,我的代碼失敗......

preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches); 

我需要什麼模式? :/

回答

1

我認爲這是因爲\w運算符不匹配空格。因爲等號後面的所有內容都必須適合在關閉之前%,它必須匹配括號內的任何內容(否則整個表達式不匹配)。

這段代碼爲我工作:

$str = '{%title=append me to the title%}'; 
preg_match('/{%title=([\w ]+)%}/', $str, $matches); 
print_r($matches); 

//gives: 
//Array ([0] => {%title=append me to the title%} [1] => append me to the title) 

注意的是,使用+(一個或多個)的意思是空的表達,即。 {%title=%}將不匹配。根據您對空白區域的期望,您可能希望在\w字符類之後使用\s而不是實際的空格字符。 \s將匹配製表符,換行符等

1

你可以試試:

$str = '{%title=append me to the title%}'; 

// capture the thing between % and = as title 
// and between = and % as the other part. 
if(preg_match('#{%(\w+)\s*=\s*(.*?)%}#',$str,$matches)) { 
    $title = $matches[1]; // extract the title. 
    $append = $matches[2]; // extract the appending part. 
} 

// find these. 
$find = array("/$append/","/$title/"); 

// replace the found things with these. 
$replace = array('IS GOOD','TITLE'); 

// use preg_replace for replacement. 
$str = preg_replace($find,$replace,$str); 
var_dump($str); 

輸出:

string(17) "{%TITLE=IS GOOD%}" 

注:

在你的正則表達式:/\{\%title\=(\w+.)\%\}/

  • 那裏不需要轉義%,因爲它的 不是元字符。
  • 有沒有必要逃避{}。 這些元炭,但只有當 用作的 {min,max}{,max}{min,}{num}形式的量詞。所以在你的情況下,他們是字面上的待遇。
+0

這很好。乾杯 – dave 2010-03-31 05:26:15

+0

@加里:很高興知道它的作品。既然答案對你有用,你可能想要投票贊成。此外,如果這個答案作爲所有答案中最有用的答案,您可能希望通過檢查答案旁邊的正確標記來接受答案。乾杯:) – codaddict 2010-03-31 05:33:07

1

嘗試這種情況:

preg_match('/(title)\=(.*?)([%}])/s', $string, $matches); 

匹配[1]具有YOUT標題和匹配[2]的另一部分。