[英]PHP regular expression find and append to string
我正在嘗試使用正則表達式(preg_match 和 preg_replace)來執行以下操作:
找到這樣的字符串:
{%title=append me to the title%}
然后提取title
部分append me to the title
部分。 然后我可以用它來執行 str_replace() 等。
鑒於我在正則表達式方面很糟糕,我的代碼失敗了......
preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches);
我需要什么模式? :/
我認為這是因為\\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
將匹配制表符、換行符等。
你可以試試:
$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}
的形式用作量詞時。 所以在你的情況下,他們是按字面處理的。嘗試這個:
preg_match('/(title)\=(.*?)([%}])/s', $string, $matches);
match[1] 有你的標題,match[2] 有另一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.