Replace " ’ " with " ' " in PHP

Mike R picture Mike R · Jul 5, 2012 · Viewed 17k times · Source

I'm grabbing a string from the database that could be something like String’s Title however I need to replace the with a ' so that I can pass the string to an external API. I've used just about every variation of escaped strings in str_replace() that I can think of to no avail.

Answer

pamil picture pamil · Jul 5, 2012
$stdin = mb_str_replace('’', '\'', $stdin);

Implementation of mb_str_replace() here: http://www.php.net/manual/en/ref.mbstring.php#107631

I mean this:

<?php
function mb_str_replace($needle, $replacement, $haystack) {
   return implode($replacement, mb_split($needle, $haystack));
}
echo mb_str_replace('’', "'", "String’s Title");

It may solve encoding problems.