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, $replace, $pos, strlen($needle));
}
?>
方法二、str_replace_limit
<?
function str_replace_limit($search, $replace, $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, $replace, $subject, $limit);
}
?>
大家可以结合小编之前整理的一篇文章《php关键字仅替换一次的实现函数》一起学习,相信大家会有意想不到的收获 。 |