php str_replace 替换自身
我需要替换出现的所有字母 a
、o
、i
、e
、你
与[aoieu]?
我尝试执行以下操作:
str_replace(array('a', 'o', 'i', 'e', 'u'), '[aoieu]?', $input);
但是当给它输入 black
而不是给我预期的 bl[aoieu]?ck
时,它给了我
bl[a[ao[aoi[aoie[aoieu]?]?[aoieu]?]?[aoie[aoieu]?]?[aoieu]?]?[aoi[aoie[aoieu]?]?[aoieu]?]?[aoie[aoieu]?]?[aoieu]?]?ck
如何让它不替换已经替换的东西?
I need to replace every occurrence of one of the letters a
,o
,i
,e
,u
with [aoieu]?
I tried to do the following:
str_replace(array('a', 'o', 'i', 'e', 'u'), '[aoieu]?', $input);
But when giving it input of black
instead of giving me the expected bl[aoieu]?ck
it gave me
bl[a[ao[aoi[aoie[aoieu]?]?[aoieu]?]?[aoie[aoieu]?]?[aoieu]?]?[aoi[aoie[aoieu]?]?[aoieu]?]?[aoie[aoieu]?]?[aoieu]?]?ck
How can I get it to not replace things it already replaced?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以考虑为此使用正则表达式,或者您可以创建自己的函数,一次遍历字符串一个字母。这是一个正则表达式解决方案:
或者您自己的函数(请注意,
$search
只能是单个字符或字符数组,而不是字符串 - 您可以使用strpos
或类似的构建一个也可以处理更长字符串的版本):You can consider using a regular expression for this, or you can make your own function which steps through the string one letter at a time. Here's a regex solution:
Or your own function (note that
$search
only can be a single char or an array of chars, not strings - you can usestrpos
or similar to build one which handles longer strings as well):我建议避免 preglike 函数并使用
strtr()
。此本机函数
代码:
I recommend avoiding preglike functions and using
strtr()
.This native function
Code:
你可能想尝试这个
You might want to try this
摘自文档:
Taken from the documentation:
您也许可以让 preg_replace 为您处理这个问题(请参阅 Thax、Emil 等的答案)。
否则,如果太复杂,您可以标记化:
You might be able to get preg_replace to handle this for you (see Thax, Emil, etc.'s answers).
Otherwise, if that is too complicated, you can, tokenize:
这里是:
Here it is: