PHP编程:php如何实现只替换一次或N次
《php如何实现只替换一次或N次》要点: ?我们都知道,在PHP里Strtr,strreplace等函数都可以用来替换,不过他们每次替换的时候都是全部替换,举个例子: ???? mixed preg_replace ( mixed pattern,mixed replacement,mixed subject [,int limit] ) 办法一:str_replace_once <?php function str_replace_once($needle,$replace,$haystack) { // Looks for the first occurence of $needle in $haystack // and replaces it with $replace. $pos = strpos($haystack,$needle); if ($pos === false) { // Nothing found return $haystack; } return substr_replace($haystack,$pos,strlen($needle)); } ?> 办法二、str_replace_limit <? function str_replace_limit($search,$subject,$limit=-1) { // constructing mask(s)... if (is_array($search)) { foreach ($search as $k=>$v) { $search[$k] = '`' . preg_quote($search[$k],'`') . '`'; } } else { $search = '`' . preg_quote($search,'`') . '`'; } // replacement return preg_replace($search,$limit); } ?> 年夜家可以结合小编之前整理的一篇文章《php关键字仅替换一次的实现函数》一起学习,相信年夜家会有意想不到的收获.PHP教程 欢迎参与《php如何实现只替换一次或N次》讨论,分享您的想法,编程之家 52php.cn为您提供专业教程。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |