PHP String Exercises: Get the 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:
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 :
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics