Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP นับจำนวนตัวอักษรใน String

ตัวอย่างโค้ด

<?php
$my_string = "Hi there, this is a sample ";
$len = mb_strlen($my_string);
echo "The number of characters in the string is $len";
?>

ผลลัพธ์

The number of characters in the string is 27

คำอธิบาย

  • mb_strlen() - Multi-byte Safe นับ Characters (รวม Spaces)
  • strlen() - นับ Bytes (ไม่เหมาะกับ UTF-8 Thai/Unicode)
  • ตัวแปร $len เก็บความยาว

strlen() vs mb_strlen()

<?php
$thai = "สวัสดี";
echo "strlen: " . strlen($thai) . "\n";     // 15 (bytes: 3 bytes/char * 5)
echo "mb_strlen: " . mb_strlen($thai) . "\n"; // 5 (characters)
?>

นับเฉพาะ Non-whitespace

<?php
$str = "Hi there, this is a sample ";
echo "With spaces: " . mb_strlen($str) . "\n";
echo "Without spaces: " . mb_strlen(str_replace(' ', '', $str)) . "\n";
?>

นับ Words

<?php
$str = "Hi there, this is a sample";
echo "Word count: " . str_word_count($str) . "\n";  // 6
?>