在php中要替换串中指定字符我们一般会一次全部替换,如str_replace函数,但有时只想替换第一次出现的,像文章的关键词替换了,这个如果有100个不可能出现100次啊,我只想限制几次了,下面我来给各位介绍实现方法。
例:$str='这是字符串我只替换ABC一次后面的ABC我不替换了,有没有办法实现.';
把第一个abc替换成xyz,由于要替换的字符串是固定的,很多人想到了用str_replace()函数,看看这个函数的使用是不是我们要的.
str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
不小心还真以为是我们想要的呢,最后那个参数是返回替换发生的总次数,它是一个引用变量,而不是我要想要的指定它将替换几次,所以用str_replace()是不行的.
preg_replace()是可以实现的,可惜用了正则,代码如下:
$str=preg_replace('/abc/','abc',$str,1); echo $str;
例:显示email为从@前2位(含)开始向前隐藏4位,代码如下:
- function show_email_2($string){
- $first = strpos($string, '@');
- //var_dump($first);
- if($first==1){
- $string = '****'.$string;
- }
- if($first>1 && $first<=5){
- $string = substr_replace($string,'****',0,$first-1);
- }
- if($first>5){
- $string = substr_replace($string,'****',$first-5,4);
- }
- var_dump($string);
- return $string;
- }
- //show_email_2('22@163.com'); //输出–>****2@163.com
- //show_email_2('22@22.com'); //输出–>****2@22.com
- show_email_2('6123456@163.com'); //输出–>61****6@163.com
有没有不用正则的,嗯可以这样
- $replace='xyz';
- if(($position=strpos($str,$replace))!==false){
- $leng=strlen($replace);
- $str=substr_replace($str,'abc',$position,$leng);
- }
- echo $str;
如果我想替换到指定次数可参考下面方法,代码如下:
- <?php
- /*
- * $text是输入的文本;
- * $word是原来的字符串;
- * $cword是需要替换成为的字符串;
- * $pos是指$word在$text中第N次出现的位置,从1开始算起
- * */
- function changeNstr($text,$word,$cword,$pos=1){
- $text_array=explode($word,$text);
- $num=count($text_array)-1;
- if($pos>$num){
- return "the number is too big!or can not find the $word";
- }
- $result_str='';
- for($i=0;$i<=$num;$i++){
- if($i==$pos-1){
- $result_str.=$text_array[$i].$cword;
- }else{
- $result_str.=$text_array[$i].$word;}
- }
- return rtrim($result_str,$word);
- }
- $text='hello world hello pig hello cat hello dog hello small boy';
- $word='hello';
- $cword='good-bye';
- echo changeNstr($text,$word,$cword,3);
- //输出:hello world hello pig good-bye cat hello dog hello small boy
- ?>
实例都很好理解,如果你不想深入了解我们直接使用str_replace即可实例了.
波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
波比源码 » php 只替换第一次出现的字符串
波比源码 » php 只替换第一次出现的字符串
Good info. Lucky me I reach on your website by accident, I bookmarked it. Metropol Halı Karaca Halı Öztekin ve Selçuklu Halı Cami Halısı ve Cami Halıları Türkiye’nin En Büyük Cami Halısı Fabrikasıyız…
Good info. Lucky me I reach on your website by accident, I bookmarked it.