What is a string in PHP?
A PHP string is a sequence of characters in which a character corresponds to a byte. PHP strings cannot support Unicode strings because a byte can only represent 256 characters. To create a string in PHP, you can use: single quotes ('...'), double-quoted strings ("..."), and Heredoc syntax (<<<). PHP provides many built-in functions for interpolating, replacing, splitting, concatenating, and comparing strings. You can also convert string to lowercase, convert string to int, convert string to array and find the length of a string.
How to replace a string with a substring in PHP?
To replace a string with a substring in PHP, you can use the str_replace() function. The following is the syntax of the str_replace() function:
- $search (required): the string to search for;
- $replace (required): the string to replace with;
- $subject (required): the string or an array of strings where we want to replace;
- $count (optional): the number of replacements to perform;
PHP String Replace Examples
The following are examples of replacing strings in PHP:
Replace all occurrences of a string
The following is an example of replacing all occurrences of a string in a PHP string:
Removing a substring in a string
To remove a substring from a string, you need to pass an empty string ("...") in the $replace argument. The following is an example of removing a substring in a PHP string:
How to replace a PHP string with Regular Expression?
To replace a PHP string using a Regular Expression, you can use the preg_replace() function. The main difference between preg_replace() and str_replace() functions is that preg_replace() will perform Regular Expression pattern matching, while str_replace() will replace a specific string with another string, and it will be much faster and more efficient. The following is the syntax of the preg_replace() function:
- $pattern (required): a pattern containing a Regular Expression to search for content;
- $replacement (required): the string to replace;
- $subject (required): string to perform the replacement;
- $limit (optional): specifies the maximum possible number of replacements for each pattern. The default is -1, which means unlimited;
- $count (optional): the variable will contain the number of replacements performed after the function is executed.
Replacing PHP String with Regular Expressions Examples
The following are examples of replacing a PHP string using Regular Expressions in PHP:
Using the Regular Expression to replace the first occurrence of a string
The following is an example of replacing the first occurrence in a PHP string using Regular Expressions:
Using Regular Expressions to replace string, case-insensitively:
To replace a case-insensitive string with Regex, you need to add an "i" anchor to the Regular Expression:
Using the Regular Expressions function to remove all spaces
The following is an example of removing all spaces in a PHP string using Regular Expressions: