preg_replace自定义范围

时间:2011-06-12 14:11:07

标签: php preg-replace

用户输入存储在变量$ input中。

所以我想使用preg replace来交换来自用户输入的字母,这些字母的范围是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)

但是这段代码不起作用。

如果有人对如何使这项工作有任何建议,那就太棒了。感谢

4 个答案:

答案 0 :(得分: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 :(得分: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
);

答案 2 :(得分:3)

您可以改为使用strtr(),这可以解决替换已替换的值的问题。

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

$inputyahoo,输出为oyruu,符合预期。

答案 3 :(得分:1)

给出的解决方案的一个潜在问题是每个角色可能会发生多次替换 。例如。 'a'被'y'取代,并且在同一语句中'y'被'o'取代。因此,在上面给出的例子中,'aaa'变成'ooo',而不是'yyy'可能是预期的。 'yyy'也变成'ooo'。结果字符串基本上是垃圾。如果需要的话,你永远无法将其转换回来。

你可以使用两个替换来解决这个问题。

在第一次替换时,将$regular字符替换为$input中不存在的一组中间字符序列。例如。 'a'到'[[[a]]]','b'到'[[[b]]]'等。

然后用您的$custom字符集替换中间字符序列。例如。 '[[[a]]]'到'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()的解决方案很多更好!