php replacement expressions are written in the following ways: 1. "str_ireplace($search, $replace, $str);" method; 2. "substr_replace($str, $replace, 0,5);" method .
The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
How to write replacement expression in php?
PHP String Replacement
In PHP, you can replace specific characters or substrings in a string. This is a very common function. .
str_ireplace() and str_replace() functions
str_ireplace() and str_replace use a new string to replace a specific string specified in the original string. str_replace is size sensitive. Writing, str_ireplace() is not case-sensitive, and the syntax of the two is similar.
The syntax of str_ireplace() is as follows:
mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
This function returns a string or array. This string or array is the result of replacing all search in subject with replace (ignoring case). The parameter count represents the number of times to perform the replacement.
Usage examples are as follows:
<?php $str = 'hello,world,hello,world'; $replace = 'hi'; $search = 'hello'; echo str_ireplace($search, $replace, $str); ?>
The output result of executing the above code is:
hi,world,hi,world
substr_replace() function
substr_replace( ) The syntax of the function is as follows:
mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
substr_replace() Replaces the substring qualified by the start and optional length parameters in a copy of string string using replacement.
If start is a positive number, replacement will start from the start position of string. If start is negative, the replacement will start at the start position from the bottom of string.
If the length parameter is set and is a positive number, it represents the length of the replaced substring in string. If set to a negative number, it represents the number of characters from the end of the substring to be replaced from the end of string. If this parameter is not provided, the default is strlen(string) (the length of the string). Of course, if length is 0, then the function of this function is to insert replacement at the start position of string.
The usage example of this function is as follows:
<?php $str = 'hello,world,hello,world'; $replace = 'hi'; echo substr_replace($str, $replace, 0,5); ?>
The execution result of the above code is:
hi,world,hello,world
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to write replacement expression in php. For more information, please follow other related articles on the PHP Chinese website!