1

我有这个简单的代码来计算字符串中的标点符号。即“有 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 ) 
4

1 回答 1

2

它可能不是多字节兼容的。PHP doc page 上有一条有用的评论str_split,建议如下:

function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
于 2012-04-29T02:05:45.080 回答