Replaces the nth occurrence of a character in a string without a regular expression

Source: Internet
Author: User
For example there is a string: $a = ' Hello world hello pig hello cat Hello dog hello small boy ';
Then I want to change the 3rd occurrence of Hello into good-bye, for example:
' Hello World Hello pig good-bye cat Hello dog hello small boy ';
In this case, I will not find the PHP built-in function 1:30, and in the case of requirements can not use regular expressions, it is written this simple small function, if you have a good built-in function recommendation, welcome message:)
Go from PHP interview question: http://phpmst.com/
    1. !--? php /*
    2. * $text is the input text;
    3. * $word is the original string;
    4. * $cword is the string to be replaced;
    5. li> * $pos refers to the position of the nth occurrence of $word in $text, starting from 1, counting
    6. */
    7. function Changenstr ($text, $word, $cword, $pos =1) {
    8. li> $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
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.