Home  >  Article  >  Backend Development  >  Replace the Nth occurrence of characters in a string without using regular expressions

Replace the Nth occurrence of characters in a string without using regular expressions

WBOY
WBOYOriginal
2016-07-25 09:02:321341browse
For example, there is a string: $a='hello world hello pig hello cat hello dog hello small boy';
Then I want to change the hello that appears for the third time to good-bye, for example:
'hello world hello pig good-bye cat hello dog hello small boy';
In this case, I couldn’t find PHP’s built-in function for a while, and I wrote this simple little function when I was required not to use regular expressions. If you have any recommendations for good built-in functions, please leave a message:)
Reprinted from PHP interview questions: http://phpmst.com/
  1. /*
  2. * $text is the input text;
  3. * $word is the original string;
  4. * $cword is the string that needs to be replaced;
  5. * $pos refers to $word The position of the Nth occurrence in $text, starting from 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. //Output: hello world hello pig good-bye cat hello dog hello small boy
  27. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn