Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Đếm số lần xuất hiện của ký tự trong chuỗi PHP

Ví dụ

<?php
$str = "welcome to tutorials point";
$str = str_replace(" ", "", $str); // bỏ khoảng trắng
$arr = str_split($str); // tách thành mảng ký tự
$output = [];
foreach ($arr as $key => $val) {
    if (!isset($output[$val])) {
        $output[$val] = 1;
    } else {
        $output[$val] += 1;
    }
}
foreach ($output as $char => $number) {
    echo $char . " appears " . $number . " times\n";
}
?>

Kết quả

w appears 1 times
e appears 2 times
l appears 2 times
c appears 1 times
o appears 4 times
m appears 1 times
t appears 4 times
u appears 1 times
r appears 1 times
i appears 2 times
a appears 1 times
s appears 1 times
p appears 1 times
n appears 1 times