Friday, April 8, 2016

How to remove underscore from a string in php


To remove underscore from a string in php, we can use the str_replace function, in fact you can also remove other character or other string, so not just underscore.

The str_replace function takes three input parameters, four actually but the most important is the first three input parameters.

The first one is the character/string that you want to remove/replace, the second is the character/string that will be replacing, the third is the string or variable that contains the string.

str_replace()

str_replace($remove, $replace, $the_string)

Example:
$original = 'lets_go_to_the_beach_today_my_friend';

$replace = str_replace('_', ' ', $original);

echo $replace;

The code above will output:
lets go to the beach today my friend

If you want, you can also count how many times the string being replaced/removed, using the fourth parameter, let's say $count.

Example:
$original = 'lets_go_to_the_beach_today_my_friend';

$replace = str_replace('_', ' ', $original, $count);

echo $count;

FYI :
In mysql database there is a similar function called replace(), which works exactly the same as str_replace() on php, only the parameter position is little different. So if you want to do it on a query you can use mysql replace() function.

No comments:

Post a Comment