PHP str_replace函数与数组循环 [英] PHP str_replace with for loop from array

查看:536
本文介绍了PHP str_replace函数与数组循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有一个str_replace函数,我想要做的,是采取从一个数组的值,然后再拍摄下一张更换字狗。所以基本上我想要的$字符串为:

Ok I have a str_replace and what I want to do, is take values from an array, and take the next piece to replace the word "dog" with. So basically I want the $string to read:

鸭子吃了猫和猪吃黑猩猩

"The duck ate the cat and the pig ate the chimp"

<?php
$string = 'The dog ate the cat and the dog ate the chimp';
$array = array('duck','pig');
for($i=0;$i<count($array);$i++) {
    $string = str_replace("dog",$array[$i],$string);
}
echo $string;
?>

这code只是返回:

鸭子吃了猫,鸭子吃黑猩猩

"The duck ate the cat and the duck ate the chimp"

我试过几件事情,但没有工作。任何人有什么想法?

I tried several things but nothing works. Anyone have any ideas?

推荐答案

编辑:对不起,错误的答案早。这会做到这一点。否 str_replace转换,没有 preg_replace ,只是原始,快速字符串搜索和拼接:

Sorry for the erroneous answer earlier. This'll do it. No str_replace, no preg_replace, just raw, fast string searching and splicing:

<?php
$string = 'The dog ate the cat and the dog ate the chimp';
$array = array('duck', 'pig');
$count = count($array);
$search = 'dog';
$searchlen = strlen($search);
$newstring = '';
$offset = 0;
for($i = 0; $i < $count; $i++) {
    if (($pos = strpos($string, $search, $offset)) !== false){
        $newstring .= substr($string, $offset, $pos-$offset) . $array[$i];
        $offset = $pos + $searchlen;
    }
}
$newstring .= substr($string, $offset);
echo $newstring;
?>

P.S。不是一个大问题在这个例子中,但你应该保持计数()你的循环之外。有了它,你有它,它就会被执行每次迭代并不仅仅是调用一次事先慢。

p.s. Not a big deal in this example, but you should keep count() outside your loop. With it where you had it, it gets executed every iteration and is slower than just calling it once beforehand.

这篇关于PHP str_replace函数与数组循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆