I want to extract the first word of a variable from a string. For example, take this input:
<?php $myvalue = 'Test me more'; ?>
The resultant output should be Test
, which is the first word of the input.
How can I do this?
Advertisement
Answer
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