View Full Version : Foreign character issue when using str_replace

01-24-2012, 06:57 PM
Hi, I'm trying to use str_replace to replace some German characters with their ASCII equivalents, like so:

$description = str_replace("%๖%", "ö", $description);

And I also tried

$description = str_replace("%๖%", "๖", $description);

I checked in the database and it doesn't show as the correct character- it shows as รถ (and outputs as that)

I need to be able to input / output German characters correctly in my form- I was hoping str_replace would do the job but it seems that it doesn't.

My pages all have UTF-8 encoding in the header (I've heard that sometimes the issue is non-UTF encoding)

I also made sure my mySQL db was UTF-8 encoded throughout, but still no joy.

Any ideas?

01-24-2012, 09:33 PM
What charset is your database in?

01-24-2012, 09:56 PM
It *was* in Latin but I changed the whole database to UTF-8 (general) and tested again- it's still doing the same thing unfortunately...

I made the table itself, each of the table columns (aside from the primary key which autoincrements), and the database all UTF-8 General.

I also added this to my db connection include:


- and interestingly it now looks ok *in the database* record, but it still isn't outputting. I tried changing the output variable as follows, but it didn't work:

$description = $row["Description"];
$descriptionclean = htmlentities($description, ENT_QUOTES);


01-25-2012, 01:10 PM
Try adding the charset to the htmlentities: $descriptionclean = htmlentities($description, ENT_QUOTES, 'UTF-8');. Also, try to avoid using str_replace at all, I'm *quite* sure that str_replace is only an 8 bit handling for the characters, and you'd have to use the mbstring equivalent to deal with the multibyte charsets. From the sounds of it, you just want to display it so forcing the charset I'd expect would work without the need of strreplace at all.

01-25-2012, 01:29 PM
I also added this to my db connection include:

Execute the following query before all insert/fetch operations

mysql_query("SET NAMES 'utf8'"); and you don't need any str_replace() for this. See http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html

01-25-2012, 08:50 PM
Thanks, that seems to work perfectly. I'll use that output across all the forms that need it.

Thanks again to Fou-lu and Abduraooft. :)