First Word
Write a PHP function that extracts the first word from a string. Words are separated by spaces. If the string is empty, return an empty string.
Use explode(' ', $text) to split the string into words. The first element [0] contains the first word. For an empty string, explode returns an array containing one empty string, so check for empty input first.
Edge cases include empty strings (return ''), strings with leading spaces (explode includes empty elements), and single-word strings (return the whole string). The function should handle multiple spaces between words.
Extracting the first word from a string is a common text processing task. The explode() function splits a string by a delimiter, returning an array of substrings. After trimming whitespace with trim(), the first element of the resulting array contains the first word.
PHP's explode() is similar to split() in other languages. The trim() function removes leading and trailing whitespace, preventing empty first elements when the input has leading spaces. This technique is used in parsing commands, extracting names, and text analysis.
Edge cases include empty strings (return ''), strings with only whitespace (return '' after trim), and single-word strings (return the word).
Example Input & Output
Algorithm Flow

Solution Approach
Trim the input with trim() to remove leading/trailing spaces. Use explode(' ', $text) to split into words. Return $words[0] if it exists, otherwise return empty string.
For strings with multiple spaces, you can use preg_split('/\s+/', $text) which splits on any whitespace sequence, or array_filter after explode to remove empty elements.
Edge cases: empty string returns '', single word returns that word.
Time O(n), Space O(n).
The explode() and trim() combination is a robust approach for extracting the first word. For more complex whitespace handling, preg_split() with a regex pattern can split on any whitespace sequence, not just single spaces.
Best Answers
<?php
function firstWord($text) {
$trimmed = trim($text);
if ($trimmed === '') return '';
$parts = explode(' ', $trimmed);
return $parts[0];
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
