[英]How to replace all occurrences of the same search string with different values
假设我们有这段文字
$str = "Text {abc} text text text {abc}";
我想用不同的值替换所有出现的{abc},因此在最后的$ str中应该是例如:
"Text DOG text text text CAT";
我为您编写了自定义函数:)
function myReplaceFunc($needed, $str, $values)
{
$strArray = explode($needed, $str);
$replacedStr = '';
$i = 0;
foreach($strArray as $key => $str){
$replacedStr = $str != '' ? $replacedStr . $str . $values[$i] : $replacedStr;
$i = $str != '' ? $i + 1 : $i;
}
return $replacedStr;
}
echo myReplaceFunc('{abc}', 'Text {abc} text text text {abc}', ['DOG', 'CAT'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.