Home  >  Article  >  Backend Development  >  PHP implements the method of replacing only once or N times

PHP implements the method of replacing only once or N times

墨辰丷
墨辰丷Original
2018-06-06 15:08:142489browse

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] = &#39;`&#39; . preg_quote($search[$k],&#39;`&#39;) . &#39;`&#39;;
}
}
else {
$search = &#39;`&#39; . preg_quote($search,&#39;`&#39;) . &#39;`&#39;;
}
// 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!

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