Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to find the first word of a sentence
To find the first word of a sentence in PHP, you can use the built-in strtok() function. This function splits a string based on a delimiter and returns the first token.
Example
Here's how to extract the first word from a sentence ?
<?php
$my_string = 'Hi there, this is a sample statement';
echo "The first word of the string is " . strtok($my_string, " ");
?>
Output
The first word of the string is Hi
How It Works
The strtok() function splits the string at the first occurrence of the specified delimiter (space in this case). It returns only the first token, which is the first word before any space character.
Alternative Methods
Using explode()
You can also use the explode() function to achieve the same result ?
<?php
$my_string = 'Hello world, welcome to PHP';
$words = explode(" ", $my_string);
echo "The first word is: " . $words[0];
?>
The first word is: Hello
Using substr() and strpos()
Another approach combines substr() and strpos() functions ?
<?php
$my_string = 'Welcome to TutorialsPoint';
$space_position = strpos($my_string, " ");
$first_word = substr($my_string, 0, $space_position);
echo "First word: " . $first_word;
?>
First word: Welcome
Conclusion
The strtok() function is the most efficient method for extracting the first word from a sentence. Alternative methods like explode() and substr() with strpos() provide more flexibility when working with string manipulation tasks.
