In the last article, we introduced "Converting php variables to json format data". In this article, we will introduce strings. String is a common data type that is operated during php
. For substring operations, php
has built-in str_replace()
. This article will show you Let’s take a look. First, let's take a look at the syntax of the str_replace()
function.
str_replace ( mixed $search , mixed $replace , mixed $subject , int &$count = ? )
$search: The target that needs to be searched
$replace: The value that needs to be replaced with the target
$subject: String or array to be processed
$count: Optional, the number of times replacement occurs
Return value: This function returns the replaced array or string.
Code example:
1. The parameters are all strings
<?php $str="Chinese php.com is better"; $str2 = str_replace("com", "cn",$str,$count); echo $str.",经过".$count."次替换后,变为:".$str2; ?>
输出:Chinese php.com is better,经过1次替换后,变为:Chinese php.cn is better
2. The parameters are all arrays
<?php $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject);
输出:F
Recommendation: 《2021 Summary of PHP interview questions (Collection)》《php video tutorial》
The above is the detailed content of Detailed explanation of str_replace() substring replacement function. For more information, please follow other related articles on the PHP Chinese website!