Before first space / after last space

Posted on 2009-03-29
Last Modified: 2012-05-06
I want to find everything before first space:

     "Hello There World"

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

Question by:hankknight
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3

Expert Comment

ID: 24014046
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


Accepted Solution

youssefomar earned 500 total points
ID: 24014085
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


Expert Comment

ID: 24014094
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


Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Ajax and PHP 9 54
What is define("__APPROOT__", __DIR__); 6 33
PHP Underscores vs. Directory separators 5 29
blocking the posted data from outside of my domains 8 25
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question