>  기사  >  백엔드 개발  >  정규식을 사용하지 않고 문자열에서 N번째 문자 바꾸기

정규식을 사용하지 않고 문자열에서 N번째 문자 바꾸기

WBOY
WBOY원래의
2016-07-25 09:02:321338검색
比如有一个字符串:$a='hello world hello pig hello cat hello dog hello small boy';
然后想将第3次出现的hello 改变成为good-bye,比如:
'hello world hello pig good-bye cat hello dog hello small boy';
这样的情况,我一时半会没找到PHP的内置函数,而且在要求不能使用正则表达式的情况下,就编写了这个简易的小函数,如果大家有好的内置函数推荐,欢迎留言:)
转自PHP面试题: http://phpmst.com/
  1. /*
  2. * $text是输入的文本;
  3. * $word是原来的字符串;
  4. * $cword是需要替换成为的字符串;
  5. * $pos是指$word在$text中第N次出现的位置,从1开始算起
  6. * */
  7. function changeNstr($text,$word,$cword,$pos=1){
  8. $text_array=explode($word,$text);
  9. $num=count($text_array)-1;
  10. if($pos>$num){
  11. return "the number is too big!or can not find the $word";
  12. }
  13. $result_str='';
  14. for($i=0;$i<=$num;$i ){
  15. if($i==$pos-1){
  16. $result_str.=$text_array[$i].$cword;
  17. }else{
  18. $result_str.=$text_array[$i].$word;}
  19. }
  20. return rtrim($result_str,$word);
  21. }
  22. $text='hello world hello pig hello cat hello dog hello small boy';
  23. $word='hello';
  24. $cword='good-bye';
  25. echo changeNstr($text,$word,$cword,3);
  26. //输出:hello world hello pig good-bye cat hello dog hello small boy
  27. ?>
复制代码


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.