一、在PHP中替换有三种方式
1、strstr
2、str_replace
3、preg_match
都可满足你的需要
二、效率
function f1_strtr() {
for($i=0; $i<1000000; ++$i) {
$new_string = strtr("aboutdealers.com", array(".com" => ""));
}
return $new_string;
}
function f2_str_replace() {
for($i=0; $i<1000000; ++$i) {
$new_string = str_replace( ".com", "", "aboutdealers.com");
}
return $new_string;
}
$start = microtime(true);
$strtr = f1_strtr();
$stop = microtime(true);
$time_strtr = $stop - $start;
$start = microtime(true);
$str_replace = f2_str_replace();
$stop = microtime(true);
$time_str_replace = $stop - $start;
echo 'time strtr : ' . $time_strtr . "\tresult :" . $strtr . "\n";
echo 'time str_replace : ' . $time_str_replace . "\tresult :" . $str_replace . "\n";
echo 'time strtr > time str_replace => ' . ($time_strtr > $time_str_replace);
?>
--------------------------------------
time strtr : 3.9719619750977 result :aboutdealers
time str_replace : 2.9930369853973 result :aboutdealers
time strtr > time str_replace => 1
str_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:
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>
I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)
To make this work, use "strtr" instead:
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
This returns: "ZDDB"
四、结论
所以一般用str_replace , 需要正匹配的时候用preg_match