Home » Php » string – PHP – Getting rid of curly apostrophes

string – PHP – Getting rid of curly apostrophes

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

Why not just do this:

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

?

Answer:

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);