w3resource

PHP String Exercises: Get the first word of a sentence


18. Get First Word of a Sentence

Write a PHP script to get the first word of a sentence.

Original String : 'The quick brown fox'

Visual Presentation:

PHP String Exercises: Get the first word of a sentence

Sample Solution:

PHP Code:

<?php
$s = 'The quick brown fox';
// Define the original string.

$arr1 = explode(' ',trim($s));
// Split the string into an array using space as the delimiter after removing leading and trailing whitespace.

echo $arr1[0]."\n";
// Output the first element of the resulting array.
?>

Output:

The

Explanation:

The above PHP code snippet takes the string 'The quick brown fox', trims any leading or trailing whitespace, and then splits it into an array using the space ' ' as the delimiter. The explode() function splits a string into an array by breaking it into substrings based on a specified delimiter. Here, it creates an array $arr1 containing the words 'The', 'quick', 'brown', and 'fox'. Finally, it echoes out the first element of the resulting array, which is 'The'.

Flowchart :

Flowchart: Get the first word of a sentence

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract the first word from a sentence using strtok() or explode().
  • Write a PHP function to return the first token of a sentence, delimiting by spaces and punctuation.
  • Write a PHP program to display the first word of a multi-sentence string and handle extra whitespace gracefully.
  • Write a PHP script to separate and output the first word from a sentence and then also output the remainder of the sentence.

Go to:


PREV : Insert a String at a Specified Position.
NEXT : Remove Leading Zeroes from a String.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.