How to replace words using string function in php

by Lalita 24-Jun-19

0 352


If you want to change or replace the words, just use str_replace() function instead of using regex i.e regular expression. Using str_replace is easy to use and faster than using regular expressions.

str_replace can be used in many ways, here are some examples given below:

In str_replace function four parameters are used.

str_replace(find,replace,string,count);

1. find: used to find the values in the string
2. replace: used to replace the value where you are finding the value
3. string: the whole string in which you finding and replacing the values
4. count: used to count the number of replacements <!-- Not mandatory -->

<?php
// when you want to change a specific word
$mystring="Hey here I'm using string replace.";
echo str_replace("string replace", "str_replace",$mystring);
?>

Output:
Hey here I'm using str_replace.

How to replace words using string function in php


<?php
// when you replace expressions or space in the string
// also you can count the number of replacements

$mystring="Hey here I'm using string replace.";
echo str_replace(" ", "-",$mystring);
?>

Output:
Hey-here-I'm-using-string-replace.

How to replace words using string function in php


<?php
// also you can count the number of replacements

$mystring="Hey here I'm using string replace.";
echo str_replace(" ", "*", $mystring, $x);
echo '<br>'.$x;
?>

Output:
Hey*here*I'm*using*string*replace.
5 <!-- 5 is showing the number of string replacements -->

How to replace words using string function in php


Share:


Comments

    Waiting for your comments

Leave a Reply