The str_replace()
function in PHP replaces all occurrences of a search string with a replacement string. for example, when you try replacing spaces with minus signs(-) in PHP.
e.g: PHP MySQL Tutorial to PHP-MySQL-Tutorial.
In PHP to replace all spaces with minus signs(-) or plus(+) use the str_replace() method.
Replace Whitespace with Hyphen (-)
Removing white space is quite useful for manipulating strings, especially when you working with a URL Rewriting - htaccess project link below.
Example: https://tapgen.xyz/quotation/120/How-to-resize-image-before-upload-in-PHP
$text = " How to resize image before upload in PHP ";
$replacedText = str_replace(" ", "-", $text);
echo $replacedText; // Outputs: How-to-resize-image-before-upload-in-PHP
The output will show all spaces in the hyphen.
Definition and Usage of
The str_replace()
function accepts four parameters, of which 3 are mandatory and one is optional.
Here’s the basic syntax: str_replace(" ", "-", $text);
- $search: The value to search for.
- $replace The value to replace with. In our example, we replace with (-). but we can replace it with another string like an underscore, plus
- $subject: The string or array of strings to perform the replacement on.
// Replace all occurrences of "apple" with "orange"
$result = str_replace("apple", "orange", "I like apple pie and apple sauce.");
echo $result; // Outputs: I like orange pie and orange sauce.
Outputs: Apple with change or replace to orange in that example.
The str_replace() function is straightforward but powerful for performing simple text replacements in PHP.
=================================