php中str_replace替换实例讲解
在对于字符串的替换上,我们已经学过了不少的方法。但在做练习题的时候,我们会对多个字符串进行替换。从方法的实用性来说,str_replace就非常适合处理多个字符串的替换问题。下面我们就php中str_replace的概念、语法、参数、返回值进行讲解,然后带来替换的实例分享。
1、概念
str_replace()函数以其他字符替换字符串中的一些字符(区分大小写)。
该函数区分大小写。请使用str_ireplace()函数执行不区分大小写的搜索。
2、语法
str_replace(find,replace,string,count)
3、参数
Find、replace、string、count
4、返回值
返回带有替换值的字符串或数组。
5、实例
创建一个PHP示例文件;然后通过“tr_replace($vowels,"","HelloWorldofPHP");”方法替换多个字符串即可。
echostr_replace(array("m","i"),array("n","z"),"mynameisjim!")
echostr_replace(array('m','i'),'n',"mynameisjim!");
$vowels=array("a","e","i","o","u","A","E","I","O","U");
$onlyconsonants=str_replace($vowels,"","HelloWorldofPHP");
echo$onlyconsonants;
知识点扩展:
PHP利用str_replace防注入的方法
','>',$string);
$string=str_replace("{",'',$string);
$string=str_replace('}','',$string);
$string=str_replace('','',$string);
return$string;
}
?>
$val)$string[$key]=new_addslashes($val);
return$string;
}
?>
-1)?$safestep:1;
if($safestep==1){
$str=preg_replace("#script:#i","script:",$str);
$str=preg_replace("#<[/]{0,1}(link|meta|ifr|fra|scr)[^>]*>#isU",'',$str);
$str=preg_replace("#[]{1,}#",'',$str);
return$str;
}elseif($safestep==2){
$str=addslashes(htmlspecialchars(stripslashes($str)));
$str=preg_replace("#eval#i",'eval',$str);
$str=preg_replace("#union#i",'union',$str);
$str=preg_replace("#concat#i",'concat',$str);
$str=preg_replace("#--#",'--',$str);
$str=preg_replace("#[]{1,}#",'',$str);
return$str;
}else{
return$str;
}
}
?>
/','',$text);
//完全过滤动态代码
$text= preg_replace('/|?'.'>/','',$text);
//完全过滤js
$text=preg_replace('/