php str_按数组替换数组
字符串替换两个数组仅替换第一次出现的每个数组php str_按数组替换数组,php,arrays,replace,Php,Arrays,Replace,字符串替换两个数组仅替换第一次出现的每个数组 $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
$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
字符串按数组第四和第六次替换数组无法替换它已重复,必须是第一次出现,才能替换?不幸的是
stru replace
没有限制替换次数的内置选项。您可以改用preg\u 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
str_replace
期望第一个参数中的针是唯一的(在某种程度上)。因此,它不会查找第二次出现的Book
,因为一旦找到Book
,它就会在array1
中搜索它的替换索引,并立即返回匹配项
要克服此问题,您可以:
- 将实际句子拆分为标记
- 使用检查
中每个令牌的值array2
- 这将返回索引。将标记值替换为值
在
中的此索引处,然后在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);
简单方法:
- 使用
分解(分隔符,字符串)
将$text
转换为数组$output
,并将分隔符转换为空格
,然后在其上循环
- 使用var
$i
跟踪可替换字的位置
- 在foreach pass by reference
和中,可以更改
- 检查
$array2
中的$word
,如果是,则使用$array1
中的相应数字进行更改,并递增$i
- 用
内爆(胶水,碎片)
将单词连接起来
$text='这本书是由狗和猫读的,然后书显示苹果不是狗';
$array1=数组('1','2','3','4','5','6');
$array2=数组('Book','Dog','Cat','Book','Apple','Dog');
$output=分解(“”,$text);
$i=0;
foreach($output as&$word){
if(在数组中($word,$array2)){
$word=$array1[$i];
$i++;
}
}
echo内爆(“”,$output);
打印:
我教你/
它做什么?它只是preg\u match
所需正则表达式的分隔符。如果您从未使用过正则表达式,您可以搜索大量有关正则表达式的文档,您可以从这里开始:
//The 1 has read by 2 and 3 then 4 show 5 not 6