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

PHP หาคำแรกของประโยค

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

<?php
$my_string = 'Hi there, this is a sample statement';
echo "The first word of the string is " . strtok($my_string, " ");
?>

ผลลัพธ์

The first word of the string is Hi

คำอธิบาย

  • strtok($string, $delimiter) ตัด String ด้วย Delimiter
  • ครั้งแรกส่ง String 全体 ครั้งต่อไปส่งแค่ Delimiter
  • คืนค่า Token แรก (ก่อน Delimiter แรก)

วิธีอื่นๆ

1. explode()

<?php
$words = explode(" ", $my_string);
echo $words[0];  // Hi
?>

2. strstr() / strchr()

<?php
echo strstr($my_string, " ", true);  // Hi (PHP 5.3+)
?>

3. Regex

<?php
preg_match('/^\S+/', $my_string, $matches);
echo $matches[0];  // Hi
?>

การเปรียบเทียบ

MethodProsCons
strtok()Memory efficient (ไม่สร้าง Array)Stateful - ใช้ซ้ำยาก
explode()Simple, ได้ Array ทั้งหมดMemory สำหรับ String ใหญ่
strstr(..., true)Clean, One-linerPHP 5.3+
preg_match()Flexible PatternSlow สำหรับงานง่าย