tags:

views:

41

answers:

3

I was wondering how can I convert user submitted data that contains an & to and using PHP before its stored in the database.

+4  A: 

Use str_replace

$after = str_replace('&', 'and', $before);

Note that this will perform a straightforward replacement, hence (as seen on ideone.com):

$text = "ben & jerry, vanilla&coke";

echo str_replace('&', 'and', $text)."\n";
# ben and jerry, vanillaandcoke

If you want to insert spaces when there previously wasn't, then you may want to use regular expressions function like preg_replace as follows:

echo preg_replace('/\s*&\s*/', ' and ', $text)."\n";
# ben and jerry, vanilla and coke

The pattern \s* is the regex pattern for "zero or more" (*) of whitespace characters (\s). In other words, this will replace &, including any preceding and following whitespaces (of any length), and replace it with ' and '.

polygenelubricants
+1  A: 

You could do it like this:

$str = str_replace("&", "and", $str);
Whit
A: 

Using str_replace (if your data is in a single character encoding) or mb_ereg_replace (preceded by mb_regex_encoding) otherwise.

Note, however, that str_replace is (in this case) safe for UTF-8.

Artefacto