我有这个简单的代码来计算字符串中的标点符号。即“有 2 个逗号,3 个分号……”等。但是当它看到一个破折号 (—) 时,它就不起作用了。请注意,它不是连字符 (-),我不在乎那些。
em-dash 有什么特别之处,使它在 PHP 字符串和/或数组键中变得奇怪吗?也许是一个奇怪的 unicode 问题?
$punc_counts = array(
"," => 0,
";" => 0,
"—" => 0, //exists, really!
"'" => 0,
"\"" => 0,
"(" => 0,
")" => 0,
);
// $str is a long string of text
//remove all non-punctuation chars from $str (works correctly, keeping em-dashes)
$puncs = "";
foreach($punc_counts as $key => $value)
$puncs .= $key;
$str = preg_replace("/[^{$puncs}]/", "", $str);
//$str now equals something like:
//$str == ",;'—\"—()();;,";
foreach(str_split($str) as $char)
{
//if it's a puncutation char we care about, count it
if(isset($punc_counts[$char]))
$punc_counts[$char]++;
else
print($char);
}
print("<br/>");
print_r($punc_counts);
print("<br/>");
上面的代码打印:
——
Array ( [,] => 2 [;] => 3 [—] => 0 ['] => 1 ["] => 1 [(] => 2 [)] => 2 )