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

2019-01-13 00:26发布

问题:

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?

回答1:

You can use the explode function as follows:

$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test


回答2:

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.



回答3:

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.



回答4:

You could do

echo current(explode(' ',$myvalue));


回答5:

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

$words=str_word_count($myvalue, 1);
echo $words[0];


回答6:

Just in case you are not sure the string starts with a word...

$input = ' Test me more ';
echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test


回答7:

<?php
  $value = "Hello world";
  $tokens = explode(" ", $value);
  echo $tokens[0];
?>

Just use explode to get every word of the input and output the first element of the resulting array.



回答8:

Using split function also you can get the first word from string.

<?php
$myvalue ="Test me more";
$result=split(" ",$myvalue);
echo $result[0];
?>


回答9:

Similar to accepted answer with one less step:

$my_value = 'Test me more';
$first_word = explode(' ',trim($my_value))[0];

//$first_word == 'Test'


回答10:

strtok is quicker than extract or preg_* functions.



回答11:

personally strsplit / explode / strtok does not support word boundaries, so to get a more accute split use regular expression with the \w

preg_split('/[\s]+/',$string,1);

This would split words with boundaries to a limit of 1.



回答12:

$input = "Test me more";
echo preg_replace("/\s.*$/","",$input); // "Test"


回答13:

$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



回答14:

public function getStringFirstAlphabet($string){
    $data='';
    $string=explode(' ', $string);
    $i=0;
    foreach ($string as $key => $value) {
        $data.=$value[$i];
    }
    return $data;
}


回答15:

$str='<?php $myvalue = Test me more; ?>';
$s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE);
print $s[1];


回答16:

Function that will tokenize string into two parts, first word and remaining string.

Return Value: It will have first and remaining key in $return array respectively. first check strpos( $title," ") !== false is mandatory in case when string has only one word and no space in it.

function getStringFirstWord( $title ){

    $return = [];

    if( strpos( $title," ") !== false ) {

        $firstWord = strstr($title," ",true);
        $remainingTitle = substr(strstr($title," "), 1);

        if( !empty( $firstWord ) ) {
            $return['first'] = $firstWord;
        }
        if( !empty( $remainingTitle ) ) {
            $return['remaining'] = $remainingTitle;
        }
    }
    else {
        $return['first'] = $title;
    }

    return $return;
}


回答17:

You Can do it using PHP string function substr without conveting string into array.

 $string = 'some text here';
 $stringLength= strlen($string);
 echo ucfirst(substr($string,-$stringLength-1, 1));

//output S