w3resource

PHP String Exercises: Get the first word of a sentence

PHP String: Exercise-18 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to insert a string at the specified position in a given string.
Next: Write a PHP script to remove all leading zeroes from a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-string-exercise-18.php