Before first space / after last space

Posted on 2009-03-29
Medium Priority
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 2000 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

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

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

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
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…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

762 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