2012-03-08 92 views
1

你好我怎麼做一個預浸比賽上預浸匹配和替換元素

$string1 = "[%refund%]processed_by" 

$string2 = "[%refund%]date_sent" 

我要搶裏面%%位,然後取下[%item%]乾脆。只留下「proccessed_by」或「date_sent」,我已經下過了,但有點卡住了。

$unprocessedString = "[%refund%]date_sent" 

$match = preg_match('/^\[.+\]/', $unprocessedString); 
$string = preg_replace('/^\[.+\]/', $unprocessedString); 

echo $match; // this should output refund 

echo $string; // this should output date_sent 

回答

2

你的問題是在你使用preg_match功能。它返回號碼找到的匹配項。但是,如果您將一個變量作爲第三個參數傳遞給它,它會將整個模式及其子模式的匹配存儲在數組中。

所以,你可以用preg_match同時捕獲你的子模式想要的部分,這意味着你不需要preg_replace

$unprocessedString = "[%refund%]date_sent" 
preg_match('/^\[%(.+)%\](.+)/', $unprocessedString, $matches); 
echo $matches[1]; // outputs 'refund' 
echo $matches[2]; // outputs 'date_sent' 
+0

該訣竅完美。它也改進了我的邏輯。謝謝 – 2012-03-08 18:33:50