我有这个简单的代码来计算字符串中的标点符号。即“有2个逗号,3个半冒号......”等等。但是当它看到em-dash( - )时它不起作用。请注意,它不是连字符( - ),我不关心那些。
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 )
答案 0 :(得分:2)
它可能不兼容多字节。在useful comment的PHP文档页面上有一个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);
}