Johny P. Johny P. - 7 months ago 19
PHP Question

PHP replace string with an HTML entity with reg exp

I'm new to using regexp so I would like to know: How can I make a case-sensitive regular expression that matches and replaces the following in php:

#ampersand# => &
#space# =>  
#through# => ÷


Everything else like:

# ampersand#, #ampersand #, # ampersand #
# space#, #space #, # space #
# through#, #through #, # through #


should be ignored.

Any help is appreciated!

Answer

How about a function like this?

function convertToEntity($string) {
  $search = array("#ampersand#", "#space#", "#through#");
  $replace = array("&", " ", "÷");
  $newstring = str_replace($search, $replace, $string);
  return $newstring;
}