Home > Article > Backend Development > PHP implements the method of replacing only once or N times
This article mainly introduces the method of replacing only once or N times in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
Method 1: str_replace_once
IdeaFirst find the location of the keyword to be replaced, and then use the substr_replace function to directly replace it .
<?php function str_replace_once($needle, $replace, $haystack) { // Looks for the first occurence of $needle in $haystack // and replaces it with $replace. $pos = strpos($haystack, $needle); if ($pos === false) { // Nothing found return $haystack; } return substr_replace($haystack, $replace, $pos, strlen($needle)); } ?>
Method 2, str_replace_limit
Idea Still use preg_replace, but its parameters are more like preg_replace, and for certain Some special characters have been escaped for better versatility.
<? function str_replace_limit($search, $replace, $subject, $limit=-1) { // constructing mask(s)... if (is_array($search)) { foreach ($search as $k=>$v) { $search[$k] = '`' . preg_quote($search[$k],'`') . '`'; } } else { $search = '`' . preg_quote($search,'`') . '`'; } // replacement return preg_replace($search, $replace, $subject, $limit); } ?>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHP uses PDO to operate the database garbled problem solution and examples
php generates QR code with logo Implementation method
Methods and examples of implementing the Model base class based on mysqli in PHP
The above is the detailed content of PHP implements the method of replacing only once or N times. For more information, please follow other related articles on the PHP Chinese website!