2013-01-17 53 views
0

如何替換字符串中的值,該字符串中的值與數組中的值相同,但前面是\?匹配數組中的值並用替代替換

$test = "Mike (D)"; 
$array('(',')','@','-'); 

作爲()是在所述陣列$測試應該等於"Mike \(D\)";

所以基本上替換關於項目相同的項目與前綴的項目\

回答

1
$test  = "Mike (D)"; 
$find  = array('(',')','@','-'); 
$repalce = array('\(','\)','\@','\-'); 

$newphrase = str_replace($find, $repalce, $test); 
4
addcslashes($test, "()@-"); 

參見:http://php.net/manual/en/function.addcslashes.php

+0

爲什麼這給我'邁克\\(d \\)'? –

+0

我得到'Mike \(D \)' –

+0

似乎取決於'php'或'server'配置我認爲會自動添加反斜槓。 –

0

你可以試試這樣的:

foreach ($array as $needle) { 
    if(strpos($needle, $test) { 
     str_replace($needle, '\\'.$needle, $test); 
    } 
} 

或者,如果你創建一個替換字符串數組,只需使用:

$array = array('(', ')', '@',...); 
$replace = array('\(', '\)', '\@',...); 
str_replace($array, $replace, $test);