文字列内の句読点をカウントするこの単純なコードがあります。つまり、「コンマが 2 つ、セミコロンが 3 つ...」などです。しかし、全角ダッシュ (—) があると機能しません。ハイフン (-) ではないことに注意してください。それらは気にしません。
em-dash について、PHP 文字列および/または配列キーとして奇妙にする特別なことはありますか? たぶん奇妙なユニコードの問題ですか?
$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 )