Last Updated on 2022-05-21 by Clay
If we want to replace some content of a string (it is a common thing), we can use str_replace()
to do it.
Introduction of str_replace()
str_replace(
array|string $search,
array|string $replace,
string|array $subject,
int &$count = null
): string|array
There are three parameters we need to pass:
- $search: string pattern we want to match
- $replace: the new string that will replace the old content
- $subject: the full string
These three parameters can be a series or array containing a string. The last $count
is very simple replacement. For example, set it to 1, it means just replaced once and then on longer replace.
If you need to find the matching string form, you need a regular expression matching, you can use preg_replace().
If the matching string you need to find is not sensitive to the case (that is, it’s directly matched with the form of a lower or upper case), then you can use str_ireplace().
Sample Code
The following is a easiest sample code:
$text = "Hello World!";
$new_text = str_replace("World", "Clay", $text);
print_r($new_text);
Output:
Hello Clay!
References
- https://www.php.net/manual/en/function.str-replace.php
- https://www.w3schools.com/php/func_string_str_replace.asp
Read More
- [WordPress] How to Use PHP Program to List the User Data
- [WordPress] Use PHP Program To Edit A Specific Page Content
- [Solved] How to Use WordPress Core Function in External PHP File
- [Solved] Parse error: syntax error, unexpected ”lists_page” (T_CONSTANT_ENCAPSED_STRING), expecting ‘)’ in /var/www/html/wp-content/plugins/reserve-course/reserve-course.php on line 54