如何在PHP中获得一个句子的第一个单词?
我想从string中提取variables的第一个单词。 例如,采取这个input:
<?php $myvalue = 'Test me more'; ?>  结果输出应该是Test ,这是input的第一个单词。 我怎样才能做到这一点? 
您可以使用爆炸function如下:
 $myvalue = 'Test me more'; $arr = explode(' ',trim($myvalue)); echo $arr[0]; // will print Test 
 有一个string函数( strtok ),可以用来根据某些分隔符将string拆分为更小的string( 标记 )。 对于这个线程来说, Test me more的第一个单词(定义为第一个空格字符之前的任何东西)可以通过在空格字符上标记string来获得。 
 <?php $value = "Test me more"; echo strtok($value, " "); // Test ?> 
有关更多详细信息和示例,请参见strtok PHP手册页 。
如果你有PHP 5.3
 $myvalue = 'Test me more'; echo strstr($myvalue, ' ', true); 
 注意,如果$myvalue是一个单词的string,在这种情况下strstr不会返回任何东西。 一个解决scheme可能是为testingstring添加一个空格: 
 echo strstr( $myvalue . ' ', ' ', true ); 
这将始终返回string的第一个单词,即使该string只有一个单词
另一种方法是这样的:
 $i = strpos($myvalue, ' '); echo $i !== false ? $myvalue : substr( $myvalue, 0, $i ); 
或者使用爆炸,有这么多的答案使用它,我不打扰指出如何做到这一点。
你可以做
 echo current(explode(' ',$myvalue)); 
即使它有点晚,但PHP有一个更好的解决scheme:
 $words=str_word_count($myvalue, 1); echo $words[0]; 
以防万一你不确定string是以单词开始的
 $input = ' Test me more '; echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test 
 <?php $value = "Hello world"; $tokens = explode(" ", $value); echo $tokens[0]; ?> 
只需使用爆炸来获取input的每一个字,并输出结果数组的第一个元素。
使用split函数也可以从string中获取第一个单词。
 <?php $myvalue ="Test me more"; $result=split(" ",$myvalue); echo $result[0]; ?> 
  strtok比extract或preg_*function更快。 
 public function getStringFirstAlphabet($string){ $data=''; $string=explode(' ', $string); $i=0; foreach ($string as $key => $value) { $data.=$value[$i]; } return $data; } 
与接受的答案类似,less一步:
 $my_value = 'Test me more'; $first_word = explode(' ',trim($my_value))[0]; //$first_word == 'Test' 
$ input =“多testing一下”; echo preg_replace(“/ \ s。* $ /”,“”,$ input); //“testing”
 $str='<?php $myvalue = Test me more; ?>'; $s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE); print $s[1]; 
 个人strsplit / explode / strtok不支持单词边界,所以为了得到一个更加愉快的分裂使用\w正则expression式 
 preg_split('/[\s]+/',$string,1); 
这将分界线的词语限制为1。
 $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; 
问候,Ciul