问下大家 如何 对一篇文章进行对应替换
如 我们的祖国是花园,花园的花朵真鲜艳 替换成 我们的motherland是花园,花园的flowers真鲜艳 有一个数组(或者数据库)
祖国=>motherland 花朵=>flowers
我现在想到的是循环替换 ,有什么其他的更好的方法吗?
回复内容: 问下大家 如何 对一篇文章进行对应替换
如 我们的祖国是花园,花园的花朵真鲜艳 替换成 我们的motherland是花园,花园的flowers真鲜艳 有一个数组(或者数据库)
祖国=>motherland 花朵=>flowers
我现在想到的是循环替换 ,有什么其他的更好的方法吗?
一、在php中替换有三种方式
1、strstr
2、str_replace
3、preg_match
都可满足你的需要
二、效率
' . ($time_strtr > $time_str_replace);?>--------------------------------------time strtr : 3.9719619750977 result :aboutdealerstime str_replace : 2.9930369853973 result :aboutdealerstime strtr > time str_replace => 1str_replace is faster than strtr
效率上 str_replace > strtr > preg_match
三、str_replace与strtr的一些不同
be careful when replacing characters (or repeated patterns in the from and to arrays): for example: i would expect as result: zddb however, this return: zddd (because b = d according to our array) to make this work, use strtr instead: a,2 => b,3 => c,b => d); $word = zbb2; echo strtr($word,$arr); ?> this returns: zddb
四、结论
所以一般用str_replace , 需要正匹配的时候用preg_match
http://php.net/manual/en/function.str-replace.php
http://php.net/manual/zh/function.strtr.php
http://www.w3school.com.cn/php/func_string_str_replace.asp
用str_replace函数传入数组即可
$str = '我们的祖国是花园,花园的花朵真鲜艳';$result = str_replace(array('祖国','花朵'), array('motherland','flowers'), $str);echo $result;
php自带的字符串替换函数就完全满足你的要求了 建议有需求前去看下官方的手册 很多功能都有函数支持了