使用数组对同一字符串进行多次替换(可能是 preg_replace)
我需要用数组中的字符串替换某个字符串(问号)的多个实例。例如,如果我要替换的字符串出现 3 次,并且我的数组的长度为 3,则第一个将被数组中的第一项替换,第二个将被第二个替换,依此类推。
您可能会发现它与准备好的语句在 mysqli 中的工作方式。
下面是一个例子:
$myArray = array( [0] => 'yellow', [1] => 'green', [2] => 'red' ); $myString = 'banana is ?, apple is ?, tomato is ?'; $newString = someFunction($myString,$myArray); echo $newString;
然后这将返回
banana is yellow, apple is green, tomato is red
任何人都可以建议一种使用 PHP 5.2 执行此操作的方法。
I need to replace multiple instances of a certain string (question mark) with strings from an array. e.g. if the string I wish to replace appears 3 times and my array has a length of 3, the first one would be replaced by the first item in the array, the second by the second etc etc.
You may recongise it's quite similar to the way prepared statements work in mysqli.
Here's an example:
$myArray = array( [0] => 'yellow', [1] => 'green', [2] => 'red' ); $myString = 'banana is ?, apple is ?, tomato is ?'; $newString = someFunction($myString,$myArray); echo $newString;
This would then return
banana is yellow, apple is green, tomato is red
Can anyone suggest a way of doing this using PHP 5.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不使用
why not use
在 PHP 5.2 中它变得有点难看,因为你必须使用全局变量在回调之间传递信息,但在其他方面它非常灵活。使用
preg_replace_callback()
:您必须满足比数组条目更多的
?
的情况,并在每次调用时重置计数器。Adam 的观点是正确的,
sprintf()
更简洁,但您并不总是控制输入字符串。preg_replace_callback
可以满足更广泛的情况。It gets a little ugly in PHP 5.2 because you have to use global variables to pass information between callbacks but it's very flexible otherwise. Use
preg_replace_callback()
:You'd have to cater for there being more
?
s than array entries as well as reset the counter with each call.Adam is right about
sprintf()
being somewhat cleaner but you don't always control the input string.preg_replace_callback
can cater for a far wider range of circumstances.