[PHP] - str_replace 只替换一次

来源:http://www.ooso.net/archives/358

在日志里头看到这样一个查询词,“php str_replace 一次”。用户可能是在找如何利用php的str_replace只替换目标字符串的内容一次,而不是全部替换。
这是个比较小但是有点意思的问题,正好之前也做过类似的处理,当时我是直接利用preg_replace实现的。

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit] )
在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。
因为preg_replace的第四个参数可以实现替换次数的限制,所以这个问题这样处理很方便。但是在查看php.net上关于str_replace的函数评论后,从中居然也可以挑出几个有代表性的函数来。

str_replace_once
思路首先是找到待替换的关键词的位置,然后利用substr_replace函数直接替换之。

 
  
<? 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
还是利用preg_replace,只不过它的参数更象preg_replace了,而且对某些特殊字符做了转义处理,通用性更好。

 
  
<?
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 );
}
?>

转载于:https://www.cnblogs.com/hcbin/archive/2011/05/15/2047222.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值