字符串替换两个数组只替换第一次出现的每个数组
$text = 'The Book has read by Dog and Cat then Book show Apple not Dog';
$array1 =array('1','2','3','4','5','6');
$array2=array('Book','Dog','Cat','Book','Apple','Dog');
echo str_replace($array2, $array1, $text);
产出是
The 1 has read by 2 and 3 then 1 show 5 not 2
但需要输出
The 1 has read by 2 and 3 then 4 show 5 not 6
字符串替换数组第4和第6不能被替换,它已经重复了,它必须是第一次出现,只有替换可能吗?
发布于 2021-05-30 05:06:39
不幸的是,str_replace
没有一个内置的选项来限制替换的数量。您可以使用preg_replace
代替,因为这个函数作为第四参数有发生的限制。
您的代码需要考虑要替换的字符串现在是regex,所以您需要添加一个分隔符(例如,/
)。
工作守则如下:
$text = 'The Book has read by Dog and Cat then Book show Apple not Dog';
$array1 = array('1','2','3','4','5','6');
$array2 = array('/Book/','/Dog/','/Cat/','/Book/','/Apple/','/Dog/');
echo preg_replace($array2, $array1, $text, 1);
输出是
The 1 has read by 2 and 3 then 4 show 5 not 6
发布于 2021-05-30 05:09:02
str_replace
期望第一个参数中的针是唯一的(在某种程度上)。因此,它不会注意Book
的第二次出现,因为它一找到Book
,就会在array1
中搜索它的替换索引并立即返回匹配。
要克服这一问题,您可以:
array2
中使用array_search
检查每个令牌的值。array1
中此索引处的值,稍后在array1
和array2
中取消设置此索引。片段:
<?php
$text = 'The Book has read by Dog and Cat then Book show Apple not Dog';
$array1 = array('1','2','3','4','5','6');
$array2 = array('Book','Dog','Cat','Book','Apple','Dog');
$tokens = explode(" ",$text);
foreach($tokens as &$token){
$idx = array_search($token,$array2);
if($idx !== false){ // if match is found.
$token = $array1[ $idx ];
unset($array2[ $idx ]);
unset($array1[ $idx ]);
}
}
echo implode(" ",$tokens);
发布于 2021-05-30 05:30:09
简单方法:
explode(delimiter, string)
将$text
转换为数组$output
和分隔符作为空格,然后在其上循环。$i
保持可替换字的跟踪位置。&
可以改变。$word
在$array2
中,如果是这样更改与相应的数字在$array1
和增量$i
。implode(glue, pieces)
连接起来。$text = 'The Book has read by Dog and Cat then Book show Apple not Dog';
$array1 = array('1','2','3','4','5','6');
$array2 = array('Book','Dog','Cat','Book','Apple','Dog');
$output = explode(' ', $text);
$i=0;
foreach ($output as &$word) {
if(in_array($word, $array2)){
$word = $array1[$i];
$i++;
}
}
echo implode(' ', $output);
印刷:
//The 1 has read by 2 and 3 then 4 show 5 not 6
https://stackoverflow.com/questions/67761343
复制相似问题