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.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I'm not a programming specialist, but I think removing underscores is for code security. I don't know such things, which is why I prefer definitely ready solutions operating in the cloud. All in all, you can always check their price at https://grapeup.com/cloudboostr/pricing/ which is very affordable for me .

    ReplyDelete
  3. I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks! String functions php

    ReplyDelete