php字符串替换

2021-09-28
// 将$subject中的$search替换为$replace并返回替换后的结果,替换次数记录在$count中;替换区分大小写
// 如果$subject是数组,替换将在每一个数组元素上执行
// 如果$search是数组,数组中的每个元素都将$subject中的匹配替换为$replace,如果$replace为数组则一一对应,对应不上的则对应$replace最后一个,如果$replace为字符串将全部替换为$replace
str_replace($search, $replace, $subject, $count);

// 将$subject中的$search替换为$replace并返回替换后的结果,替换次数记录在$count中;替换不区分大小写
// 如果$subject是数组,替换将在每一个数组元素上执行
// 如果$search是数组,数组中的每个元素都将$subject中的匹配替换为$replace,如果$replace为数组则一一对应,对应不上的则对应$replace最后一个,如果$replace为字符串将全部替换为$replace
str_ireplace($search, $replace, $subject, $count);

// 将$string中从$start开始长度为$length的字符串替换为$replacement,返回替换后的结果,不影响原数据
// 如果$string是数组,替换将在每一个数组元素上执行
// $start为正数,替换将从string的start位置开始。如果$start为负数,替换将从string的倒数第start个位置开始
// $length为正数,表示string中被替换的子字符串的长度。如果$length为负数,表示待替换的子字符串结尾处距离string末端的字符个数,$length为0则将$replacement插入到$string的$start位置处;$length默认为$string的长度
substr_replace($string, $replacement, $start, $length = ?);
// 将字符串$str中的$from转换为$to,返回的值的长度和str的长度一样,如果$from与$to长度不相等,多余的部分将忽略
strtr($str, $from, $to);

// 转换字符串$str,转换内容为数组$replace_pairs(array('from' => 'to', ...)),返回的值的长度和str的长度一样,如果$from与$to长度不相等,多余的部分将忽略
strtr($str, $replace_pairs);

正则替换

// 将字符串$string中的匹配项$pattern正则替换为$replacement,忽略大小写
mb_eregi_replace($pattern, $replacement, $string);

// 将字符串$string中的匹配项$pattern正则替换为$replacement
mb_ereg_replace($pattern, $replacement, $string);

// 将字符串$string中的匹配项$pattern正则使用$callback方法进行替换;$callback的参数为匹配到的字符串
mb_ereg_replace_callback($pattern, $callback, $string);

 

{/if}