Before first space / after last space

I want to find everything before first space:

     "Hello There World"

I want $first to be "Hello"
I want $last to be "World"


LVL 16
hankknightAsked:
Who is Participating?
 
youssefomarConnect With a Mentor Commented:
or you use strpos and strripos to find 1st and last spaces:

<?
	$str =  "Hello There World";
	$first_space = strpos($str, " ");
	$last_space = strripos($str, " ");
	
	echo "first: " . substr($str,0,$first_space);
	echo "<br>last: " . substr($str,$last_space);
 
?>

Open in new window

0
 
youssefomarCommented:
one quick solution is to convert to array and pint first and last



<?
  arr = explode(" ", "Hello There World");
 
  echo "First: ". arr[0];
  echo "Last: " . arr[count(arr)-1];
  
 
?>

Open in new window

0
 
youssefomarCommented:
sorry I didn't type the $ before the arr variable in the 1st example, here it is again

<?
 
  $arr = explode(" ", "Hello There World");
 
  echo "First: ". $arr[0];
  echo "<br>Last: " . $arr[count($arr)-1];
?>

Open in new window

0
All Courses

From novice to tech pro — start learning today.