【问题标题】:PHP - Getting rid of curly apostrophesPHP - 摆脱卷曲撇号
【发布时间】:2009-10-22 03:32:07
【问题描述】:

我正在尝试摆脱卷曲撇号(我想是从某种富文本文档中粘贴的撇号),但我似乎遇到了障碍。下面的代码对我不起作用。

$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'.

当我从 $search 数组中删除 & 符号时,会发生替换,但显然,这不会完成工作,因为 & 符号留在字符串中。为什么 str_replace 在遇到 & 符号时会失败?

【问题讨论】:

  • 那些弯撇号称为智能引号。

标签: php string escaping


【解决方案1】:

为什么不这样做:

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

?

【讨论】:

  • 哇,这太容易了。我想我已经编码太久了!
【解决方案2】:

为了让事情正常运行,我需要一些比@cletus 所展示的示例更强大的东西。这对我有用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 2011-02-19
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2012-01-26
    相关资源
    最近更新 更多