str_replace只替换一次字符串的方法
我们都知道,在PHP里Strtr,strreplace等函数都可以用来替换,不过他们每次替换的时候都是全部替换,举个例子: mixed preg_replace ( mixed pattern,mixed replacement,mixed subject [,int limit] ) str_replace_once 代码如下: functionstr_replace_once($needle,$replace,$haystack){ //Looksforthefirstoccurenceof$needlein$haystack //andreplacesitwith$replace. $pos=strpos($haystack,$needle); if($pos===false){ return$haystack; } returnsubstr_replace($haystack,$pos,strlen($needle)); } ?> str_replace_limit 代码如下: functionstr_replace_limit($search,$subject,$limit=-1){ //constructingmask(s)... if(is_array($search)){ foreach($searchas$k=>$v){ $search[$k]='`'.preg_quote($search[$k],'`').'`'; } } else{ $search='`'.preg_quote($search,'`').'`'; } //replacement returnpreg_replace($search,$limit); } ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |