PHP implements the method of replacing only once or N times

墨辰丷
Release: 2023-03-30 08:34:01
Original
2488 people have browsed it

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));
}
?>
Copy after login

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);
}
?>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!