Example
$ Str = 'this is the string. I will only replace ABC once and I will not replace it. Is there any way to implement this. ';
Replace the first abc with xyz. Because the string to be replaced is fixed, many people think of using the str_replace () function to see if this function is required.
Str_replace (mixed $ search, mixed $ replace, mixed $ subject [, int & $ count])
Accidentally, I thought it was what we wanted. The last parameter was the total number of times the replacement was returned. It was a reference variable, instead of the number of times it would be replaced, therefore, str_replace () cannot be used.
Preg_replace () can be implemented. Unfortunately, regular expressions are used,
The code is as follows: |
Copy code |
$ Str = preg_replace ('/abc/', 'ABC', $ str, 1 ); Echo $ str; |
Example
Show email as four digits forward from the first two digits (inclusive) @
The code is as follows: |
Copy code |
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 '); // output --> *** 2@163.com // Show_email_2 ('22 @ 22.com '); // output --> *** 2@22.com Show_email_2 ('1970 @ 163.com '); // output --> 61 **** 6@163.com Is there any regex? Well, you can. $ Replace = 'XYZ '; If ($ position = strpos ($ str, $ replace ))! = False ){ $ Leng = strlen ($ replace ); $ Str = substr_replace ($ str, 'ABC', $ position, $ leng ); } Echo $ str; |
If you want to replace it with a specified number of times, refer to the following method:
The code is as follows: |
Copy code |
<? Php /* * $ Text is the input text; * $ Word is the original string; * $ Cword is the string to be replaced; * $ Pos indicates the position where $ word appears N times in $ text, starting from 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 boys '; $ Word = 'hello '; $ Cword = 'good-bye '; Echo changeNstr ($ text, $ word, $ cword, 3 ); // Output: hello world hello pig good-bye cat hello dog hello small boy ?> |
The instance is easy to understand. If you don't want to know more about it, we can simply use str_replace.