PHP - 如何去掉花式撇号

7

我正在尝试去除弯曲的撇号(我想是从某种富文本文档中复制粘贴的),但似乎遇到了障碍。下面的代码对我无效。

$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在遇到&符号时失败了呢?


3
那些弯曲的撇号被称为智能引号。 - random
2个回答

11

为什么不直接这样做:

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

?


哇,这真是太容易了。我想我编程时间太长了! - Anthony

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接