PHP - Getting rid of curly apostrophes

半世苍凉 提交于 2019-12-19 03:07:21

问题


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?


回答1:


Why not just do this:

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

?




回答2:


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


来源:https://stackoverflow.com/questions/1604891/php-getting-rid-of-curly-apostrophes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!