使用增量替换字符串一次替换一个字符串
我有字符串 $var
我需要在其中替换一些文本。第一个X
需要替换为A
,第二个X
需要替换为B
,依此类推,这是一个示例:
$var = "X X X X"; // input
// some function
echo $var //the result: "A B C D"
我尝试使用 str_replace()
,但这不起作用。
I have the string $var
in which I need to replace some text. The first X
needs to be replaced by A
, the second X
needs to be replaced by B
and so on, here is an example:
$var = "X X X X"; // input
// some function
echo $var //the result: "A B C D"
I tried with str_replace()
, but that doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用
preg_replace
的limit
参数只能替换一次。http://codepad.viper-7.com/ra9ulA
You could use
preg_replace
'slimit
argument to only replace once.http://codepad.viper-7.com/ra9ulA
您可以使用
preg_replace_callback()
:You could use
preg_replace_callback()
:其他解决方案:
此解决方案使用 preg_replace 的
$limit
参数(我们每次调用仅替换一次出现的情况)。Other solution:
This one uses the
$limit
parameter of preg_replace (we replace only one occurrence per call).不使用正则表达式
Without use of regex
还有一个解决方案(对于动态数量的 X 来说更多):
我还在模式中添加了
\b
,以仅替换独立的 X,因此“FAUX PAS X”仅替换最后 X.演示
alphabet_replace
(更模块化的形式)Yet one more solution (more for a dynamic number of Xs):
I also added the
\b
in to the pattern to only replace Xs that are free-standing, so "FAUX PAS X" only replaces the last X.demo
alphabet_replace
(more modular form)让我们也尝试一下,只是为了它;)
Lets give it a shot, too, just for the heck of it ;)
其他答案中发生了很多循环,这里有一个替代方案。
Lots of loops are happening in the other answers, here's an alternative.
所提出的问题没有提供替换的主列表,因此我假设替换的数量未知。我将增加替换值,而不是使用有限数组。
请记住,如果
$find
字符串来自不受信任的来源,则应调用preg_quote()
来转义对正则表达式引擎具有特殊含义的字符。do-while 循环:(演示)
递归函数:(演示)
滥用
finally
:(Demo)当然,以上所有技术也可以使用更加向后兼容的
++
字符串增量。 (演示)The asked question does not provide a master list of replacements, so I'll assume that the number of replacements is not known. Instead of working with a finite array, I'll increment the replacement values.
Bear in mind that if the
$find
string comes from a non-trusted source, thenpreg_quote()
should be called upon it to escape characters with special meaning to the regex engine.A do-while loop: (Demo)
A recursive function: (Demo)
An abusive use of
finally
: (Demo)Of course, all of the above techniques can also use the more backward compatible
++
string incrementation. (Demo)