![]() |
Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each method serves different use cases. Table of Content Using str_replace()A String is a collection of characters. The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by a replacement string or array of replacement strings in the given string or array respectively. We can replace the string with another by using PHP str_replace(). This method is case-sensitive, so the programmer has to take care of the case while programming and interpreting the output. Syntax: str_replace(substring,new_replaced_string,original_string); We need to provide three parameters.
Example 1: The following code replaces the string with another string.
Output: computer for computer Example 2: The following code replaces the string with empty.
Output: for Example 3: The following code replaces the string with integers.
Output: 1 for 1 Using preg_replace()Using preg_replace() in PHP, you can replace a string using regular expressions. This function allows for pattern-based search and replace operations. Example
Output Hello, PHP! Using strtr()The strtr() function in PHP translates certain characters or replaces substrings based on the provided mapping array. This function is useful when you need to replace multiple substrings or characters at once. Example:
Output I have an orange and a grape. |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |