Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Getting rid of curly apostrophes

I'm trying to get rid of curly apostrophes (ones pasted from some sort of rich text doc, I imagine) and I seem to be hitting a road block. The code below isn't working for me.

$word = "Today’s";
$search = array('„', '“', '’');
$replace = array('"', '"', "'");
$word = str_replace($search, $replace, htmlentities($word, ENT_QUOTES));

What I end up with is $word containing 'Today’s'.

When I remove the ampersands from my $search array, the replace takes place but this, obviously, will not get the job done since the ampersand is left in the string. Why is str_replace failing when it comes across the ampersands?

like image 469
Anthony Avatar asked Oct 22 '09 03:10

Anthony


2 Answers

Why not just do this:

$word = htmlentities(str_replace($search, $replace, $word), ENT_QUOTES);

?

like image 103
cletus Avatar answered Sep 21 '22 14:09

cletus


In order for me to get things working properly, I needed something a little more robust than the example @cletus laid out. Here is what worked for me:

// String full of rich characters
$string = $_POST['annoying_characters'];

// Replace "rich" entities with standard text ones
$search = array(
    '“', // 1. Left Double Quotation Mark “
    '”', // 2. Right Double Quotation Mark ”
    '‘', // 3. Left Single Quotation Mark ‘
    '’', // 4. Right Single Quotation Mark ’
    ''',  // 5. Normal Single Quotation Mark '
    '&',   // 6. Ampersand &
    '"',  // 7. Normal Double Qoute
    '&lt;',    // 8. Less Than <
    '&gt;'     // 9. Greater Than >
);

$replace = array(
    '"', // 1
    '"', // 2
    "'", // 3
    "'", // 4
    "'", // 5
    "'", // 6
    '"', // 7
    "<", // 8
    ">"  // 9
);

// Fix the String
$fixed_string = htmlspecialchars($string, ENT_QUOTES);
$fixed_string = str_replace($search, $replace, $fixed_string);
like image 43
Emerson Avatar answered Sep 22 '22 14:09

Emerson