Replacing string and spaces in PHP using str_replace function with examples
0 4187
If you want to replace characters inside a string, the str_replace() function will help you. As compared to regular expressions it is a much easier and faster way for replacing texts inside a string.
str_replace(): This function of PHP is used to replace the selected part of a string with another string. If the string occurred more than one inside the main string then all occurrences are replaced. It is an inbuilt function of PHP.
For more details about str_replace() function click here
Example 1:
Replace a specific word inside a string
<?php $str="Hello friends !!!! Welcome to our website."; $find="friends"; $replace="everyone"; $mod_str=str_replace($find,$replace,$str); echo "Old string is :<strong> $str </strong><br>"; echo "After replacement string is :<strong> $mod_str </strong>"; ?>
Output:
Example 2:
Replace whitespaces from any separator inside a string
<?php $str="Welcome to Coding Tag"; $find=" "; $replace="-"; $mod_str=str_replace($find,$replace,$str); // it will replace all occurrences of whitespaces from - echo "Old string is : <strong>$str</strong><br>"; echo "After replacement string is : <strong>$mod_str</strong>"; ?>
Output:
Example 3:
Why it is required? U r counting * manually
Count the number of replacements done by the function inside the string
<?php $str="Ravi goes to his school by bus"; $find=" "; $replace="*"; $mod_str=str_replace($find,$replace,$str,$count); // it will replace all occurrences of whitespaces from - echo "Old string is : <strong>$str</strong><br>"; echo "After replacement string is : <strong>$mod_str</strong><br>"; echo "Number of replacements are : <strong>$count</strong>"; ?>
Output:
Share:
Comments
Waiting for your comments