Monday, August 31, 2015

Replace Multiple String with PHP


Replace Multiple String In PHP
If you are working with PHP, then you would meet some problem with how to replace multiple string with a line of code. So there I will show you how to replace multiple string to make your url to be friendly.
In this case you have to know a PHP function which is call "str_replace", the below code will explain you how it work.

function replace_multiple_string($search=array(),$replace="",$string="")
{
  if(count($search) < 1)
  {
    return false;
  }
  else
  {
    return str_replace($search, $replace, $string);
  }
}

Explanation:
In the function above you would see the str_replace function which I've use to remove and replace the underscore instead of $replaces array.

 - str_replace : Replace all occurrences of the search string with the replacement string.

Usage : 

$string= "You are on_tip(and)php+website";
$search= array("_", "(", "+", ")"," ","+");

var_dump(replace_multiple_string($search,"-",$string));

Demo :

string(29) "You-are-on-tip-php-website" 
Location: Phnom Penh, Cambodia

0 comments:

Post a Comment