如何解决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)
但是此代码不起作用。
如果有人对我如何使它工作有任何建议,那就太好了。谢谢
解决方法
当
str
足够时,不要跳for1ѭ:
$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);
, 在这种情况下,使用str_replace
更有意义:
str_replace(
range(\"a\",\"z\"),// Creates an array with all lowercase letters
explode(\",\",w\"),$input
);
, 您可以改用strtr()
,这样可以解决替换已替换值的问题。
echo strtr($input,\'abcdefghijklmnopqrstuvwxyz\',\'ypltavkrezgmshubxncdijfqow\');
如预期的那样,将“ 8”作为“ 9”,输出为“ 10”。
, 给定解决方案的潜在问题是每个字符可能会发生多个替换。例如。 \'a \'被替换为\'y \',在同一条语句中,\'y \'被替换为\'o \'。因此,在上面给出的示例中,\'aaa \'变为\'ooo \',而不是预期的\'yyy \'。 \'yyy \'也变成'ooo \'。结果字符串本质上是垃圾。如果需要的话,您将永远无法将其转换回去。
您可以使用两个替代方法解决此问题。
在第一个替换中,将$regular
字符替换为$input
中不存在的中间字符集。例如。 \'a \'到\'[[[[a]]] \',\'b \'到\'[[[b]]] \',依此类推。
然后用$custom
字符集替换中间字符序列。例如。 \'[[[[a]]] \'到\'y \',\'[[[b]]] \'到\'p \',依此类推。
像这样
$regular = range(\'a\',\'y,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,$output);
编辑:
让该解决方案作为参考,但是@salathe \使用use6ѭ的解决方案要好得多!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。