Home > Article > Backend Development > PHP replaces the Nth occurrence of character code in a string_PHP tutorial
Below I have summarized some character replacement methods in PHP development, including direct replacement without regular expressions, using regular expressions to replace characters, and using PHP's own functions for replacement.
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 under the requirement that regular expressions cannot be used. If you have any recommendations for good built-in functions, please leave a message:)
The code is as follows | Copy code | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
* $word is the original string;
php function replacement The differences between commonly used regular matching functions in PHP mainly include str_replace, str_ireplace, substr_replace, preg_replace, preg_match, preg_match_all, preg_quote, preg_split, ereg_replace, eregi_replace, preg_replace, str_split. Of course, some of them cannot use regular expressions, but Because the relationship with related regular functions is ambiguous, I put them all together for comparison
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 Previous article:PHP functions ob_start(), ob_end_clean(), ob_get_contents()_PHP tutorialNext article:PHP functions ob_start(), ob_end_clean(), ob_get_contents()_PHP tutorial Related articlesSee more |