2013-07-28 38 views
0

我怎麼能條件的正則表達式來檢查是否在匹配不不復制它的preg_replace如果字符串不存在,追加

這裏有我想要什麼(假的代碼)的例子

存在串
$string = "1234"; 
$replacement = "/$1(5?)/"; // this should check if "5" is in $string, if not then add it with $1 
preg_replace('/(.*)/', $replacement, $string); 

$replacement有何建議?
我只希望使用preg_replace一行代碼中沒有其他功能

+0

這氣味像功課;爲什麼只需要preg_replace()? –

回答

3
preg_replace('/^([^5]*)$/', '${1}5', '1253'); # => 1253 
preg_replace('/^([^5]*)$/', '${1}5', '1234'); # => 12345 

注意:使用${1}5,而不是$15literal 5`區分group 1

0

你可以用strpos()

if(strpos($string, $keyword) === false) { 
$string = $string. $keyword; 
} 
+0

OP明確說'我只想使用preg_replace一行代碼沒有其他函數。 – falsetru