preg_replace 自定义范围
用户输入存储在变量 $input 中。
所以我想使用 preg Replace 来交换用户输入中从 az 开始的字母与我自己的自定义字母表。
我正在尝试的代码不起作用,如下所示:
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)
但是此代码不起作用。
如果有人对我如何使其正常工作有任何建议,那就太好了。谢谢
The user input is stored in the variable $input.
so i want to use preg replace to swap the letters from the user input that will range from a-z, with my own custom alphabet.
My code i am trying, which doesnt work is below:
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)
This code however doesnt work.
If anyone has any suggestions on how i can get this working then that would be great. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当
str
足够时,不要跳转到preg
:Don't jump for
preg
, whenstr
is enough:在这种情况下,使用
str_replace
更有意义:Using
str_replace
makes a lot more sense in this case:您可以改为使用
strtr()
,这解决了替换已替换值的问题。使用
$input
作为yahoo
,输出为oyruu
,正如预期的那样。You could instead use
strtr()
, this resolves the problem of replacing already replaced values.With
$input
asyahoo
the output isoyruu
, as expected.所给出的解决方案的一个潜在问题是每个字符可能发生多次替换。例如。 'a' 被 'y' 替换,并且在同一语句中 'y' 被 'o' 替换。因此,在上面给出的示例中,“aaa”变为“ooo”,而不是预期的“yyy”。 'yyy' 也变成 'ooo'。生成的字符串本质上是垃圾。如果有要求的话,你永远无法将其转换回来。
您可以使用两个替代品来解决这个问题。
在第一次替换时,您将
$regular
字符替换为$input
中不存在的中间字符序列集。例如。 'a' 到 '[[[a]]]'、'b' 到 '[[[b]]]' 等。然后将中间字符序列替换为您的
$custom
字符集。例如。 '[[[a]]]' 到 'y','[[[b]]]' 到 'p' 等。就像这样...
编辑:
留下这个解决方案供参考,但 @salathe 使用
strtr()
的解决方案要好得多!A potential problem with the solutions given is that multiple replacements could occur for each character. eg. 'a' gets replaced by 'y', and in the same statement 'y' gets replaced by 'o'. So, in the examples given above, 'aaa' becomes 'ooo', not 'yyy' that might be expected. And 'yyy' becomes 'ooo' as well. The resulting string is essentially garbage. You'd never be able to convert it back, if that was a requirement.
You could get around this using two replacements.
On the first replacement you replace the
$regular
chars with an intermediate set of character sequences that don't exist in$input
. eg. 'a' to '[[[a]]]', 'b' to '[[[b]]]', etc.Then replace the intermediate character sequences with your
$custom
set of chars. eg. '[[[a]]]' to 'y', '[[[b]]]' to 'p', etc.Like so...
EDIT:
Leaving this solution for reference, but @salathe's solution to use
strtr()
is much better!