2011-06-12 75 views
0

用戶輸入存儲在變量$ input中。preg_replace自定義範圍

所以我想使用preg替換來交換用戶輸入的字母,範圍從a-z,用我自己的自定義字母表。

我的代碼我試圖,這行不通低於:

preg_replace('/([a-z])/', "y,p,l,t,a,v,k,r,e,z,g,m,s,h,u,b,x,n,c,d,i,j,f,q,o,w", $input) 

此代碼但是不工作。

如果有人對我如何得到這個工作有任何建議,那就太好了。由於

回答

3

不要跳了preg,當str足夠:

$regular = range('a', 'z'); 
$custom = explode(',', "y,p,l,t,a,v,k,r,e,z,g,m,s,h,u,b,x,n,c,d,i,j,f,q,o,w"); 
$output = str_replace($regular, $custom, $input); 
+1

如果OP想用自定義設置替換大寫字符,則使用'str_ireplace'。 – anubhava 2011-06-12 14:26:29

+1

'yahoo'被翻譯成'oonii',它應該是'oyruu'。 – salathe 2011-06-12 15:55:16

3

使用str_replace,使很多更有意義在這種情況下:

str_replace(
    range("a", "z"), // Creates an array with all lowercase letters 
    explode(",", "y,p,l,t,a,v,k,r,e,z,g,m,s,h,u,b,x,n,c,d,i,j,f,q,o,w"), 
    $input 
); 
1

與解決方案給定的一個潛在問題是多個替換可能發生每個字符。例如。 'a'被替換爲'y',並且在相同的語句中,'y'被替換爲'o'。因此,在上面給出的例子中,'aaa'變成'ooo',而不是'yyy',這可能是預期的。而'yyy'也會變成'ooo'。結果字符串本質上是垃圾。如果這是一項要求,您永遠無法將其轉換回來。

你可以使用兩個替代品來解決這個問題。

在第一次替換時,用$input中不存在的一組中間字符序列代替$regular字符。例如。 'a'到'[[[a]]]','b'到'[[[b]]]'等。

然後用你的$custom字符集替換中間字符序列。例如。 '[[[α]]]' 至 'y', '[[[B]]]' 到 'P' 等

像這樣...

$regular = range('a', 'z'); 
$custom = explode(',', 'y,p,l,t,a,v,k,r,e,z,g,m,s,h,u,b,x,n,c,d,i,j,f,q,o,w'); 

// Create an intermediate set of char (sequences) that don't exist anywhere else in the $input 
// eg. '[[[a]]]', '[[[b]]]', ... 
$intermediate = $regular; 
array_walk($intermediate,create_function('&$value','$value="[[[$value]]]";')); 

// Replace the $regular chars with the $intermediate set 
$output = str_replace($regular, $intermediate, $input); 

// Replace the $intermediate chars with our custom set 
$output = str_replace($intermediate, $custom, $output); 

編輯:

留下這個解決方案供參考,不過@ salathe的解決方案使用strtr()很多更好!

3

您可以改爲使用strtr(),這樣可以解決替換已更換值的問題。

echo strtr($input, 'abcdefghijklmnopqrstuvwxyz', 'ypltavkrezgmshubxncdijfqow'); 

$input隨着作爲yahoo輸出oyruu,如所預期。

+0

+1感謝提醒我關於'strtr()'! – MrWhite 2011-06-12 16:05:01