How to get the first word of a sentence in PHP?

2019-01-13 00:11发布

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?

17条回答
戒情不戒烟
2楼-- · 2019-01-13 00:42

Even though it is little late, but PHP has one better solution for this:

$words=str_word_count($myvalue, 1);
echo $words[0];
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-13 00:42
$string = ' Test me more ';
preg_match('/\b\w+\b/i', $string, $result); // Test
echo $result;

/* You could use [a-zA-Z]+ instead of \w+ if wanted only alphabetical chars. */
$string = ' Test me more ';
preg_match('/\b[a-zA-Z]+\b/i', $string, $result); // Test
echo $result;

Regards, Ciul

查看更多
欢心
4楼-- · 2019-01-13 00:43

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.

查看更多
Melony?
5楼-- · 2019-01-13 00:43

You could do

echo current(explode(' ',$myvalue));
查看更多
Emotional °昔
6楼-- · 2019-01-13 00:54

You can use the explode function as follows:

$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
查看更多
走好不送
7楼-- · 2019-01-13 00:56
$str='<?php $myvalue = Test me more; ?>';
$s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE);
print $s[1];
查看更多
登录 后发表回答