Wednesday 22 September 2010

Replacing All Instances of a Word in string [PHP]

PHP offers a useful function called str_replace() that can be used to replace every instance of a word in a string. This function takes three compulsory arguments and one optional argument.

The first argument represents the string to be replaced, the second the replacement value and the third the target string. The function returns the modified string.

Example:

<?php
function replace($string)
{
    return str_replace("dog", "samar", $string);
}

$str = "I am dog so you call me dog";
echo $str;
echo "
".replace($str); //call replace function
?>

Output:
I am dog so you call me dog
I am samar so you call me samar

Now, what if you want to work with arrays of words to replace with, for instance, in the censoring tasks. You can write some PHP stuff as below to perform the task.

<?php
function badword_censor($string)
{
    $string = strtolower($string);
    $badwords = array("fuck","bitch","cunt","faggot","penis","vagina","dick","pussy");
// add as per your requirement
    $string = str_replace($badwords,"*censored*",$string);
    return $string;
}
$str = "Fuck you bitch.";
//echo $str;
echo "
".badword_censor($str);
?>

Output:
*censored* you *censored*.

Also, refer to the str_ireplace(), the case insensitive version of this function.
Hope this helps. :)

Edit: Thanks to cr4ck3r for the comments. Updated the post... :)