The first word of a sentence can be obtained with the help of various inbuilt functions like strtok(), strstr(), explode() and some other methods like using regular expressions.
To get the first and last characters of a string, access the string at the first and last indexes. For example, str[0] returns the first character, whereas str[str. length - 1] returns the last character of the string.
There is a string function (strtok) which can be used to split a string into smaller strings (tokens) based on some separator(s). For the purposes of this thread, the first word (defined as anything before the first space character) of Test me more
can be obtained by tokenizing the string on the space character.
<?php
$value = "Test me more";
echo strtok($value, " "); // Test
?>
For more details and examples, see the strtok PHP manual page.
You can use the explode function as follows:
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
Another example:
$sentence = 'Hello World this is PHP';
$abbreviation = explode(' ', trim($sentence ))[0];
echo $abbreviation // will print Hello
If you have PHP 5.3
$myvalue = 'Test me more';
echo strstr($myvalue, ' ', true);
note that if $myvalue
is a string with one word strstr
doesn't return anything in this case. A solution could be to append a space to the test-string:
echo strstr( $myvalue . ' ', ' ', true );
That will always return the first word of the string, even if the string has just one word in it
The alternative is something like:
$i = strpos($myvalue, ' ');
echo $i !== false ? $myvalue : substr( $myvalue, 0, $i );
Or using explode, which has so many answers using it I won't bother pointing out how to do it.
You could do
echo current(explode(' ',$myvalue));
Even though it is little late, but PHP has one better solution for this:
$words=str_word_count($myvalue, 1);
echo $words[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With