PHP - 摆脱卷曲撇号

时间:2009-10-22 03:32:07

标签: php string escaping

我正试图摆脱卷曲的撇号(从我想象的某种富文本文档粘贴的那些)我似乎正在遇到路障。以下代码对我不起作用。

$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碰到&符号时会失败?

2 个答案:

答案 0 :(得分:10)

为什么不这样做:

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

答案 1 :(得分:6)

为了让我能够正常工作,我需要的东西比@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);