How to get the first word from a string in PHP

3 Answers

0 votes
$s = "php java c# python c";
  
$arr = explode(' ', $s, 2);
 
$first_word = $arr[0];
      
echo $first_word;
 
 
 
   
/*
run:
 
php 
 
*/

 



answered Sep 6, 2019 by avibootz
0 votes
$s = "php java c# python c";
  
$arr = preg_split('/ +/', $s, 3);
 
$first_word = $arr[0];
      
echo $first_word;
 
 
 
   
/*
run:
 
php 
 
*/

 



answered Sep 6, 2019 by avibootz
0 votes
$s = "php java c# python c";
 
$first_word = substr($s, 0, strpos($s, ' '));
      
echo $first_word;
 
 
 
   
/*
run:
 
php 
 
*/

 



answered Sep 6, 2019 by avibootz

Related questions

1 answer 139 views
2 answers 182 views
2 answers 128 views
1 answer 151 views
2 answers 295 views
4 answers 429 views
1 answer 232 views
...