Delete after first space?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Gachet
Forum Newbie
Posts: 8
Joined: Wed Jan 30, 2008 4:21 am

Delete after first space?

Post by Gachet »

I would like to delete all the characters on a each line after the first occurance of a space on that line.

Example:
From this:

dog hello robot
cat monkey spanner
rabbit turtle root

dog
cat
rabbit

Thanks
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Re: Delete after first space?

Post by jayshields »

Get that data into a string, and then you could do it a couple of ways. The first thing that comes to my mind is to explode on new lines, and then explode on spaces, saving only the first chunk of the space explosion each time into a new array.

Then you can implode that array with new lines or whatever.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Delete after first space?

Post by prometheuzz »

Here's a way:

Code: Select all

$lines = 'dog hello robot
cat monkey spanner
rabbit turtle root';
echo preg_replace('/^(\S++).*+/m', '$1', $lines);
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Delete after first space?

Post by pickle »

Native string functions are generally faster than regex:

Code: Select all

 $lines='dog hello robot
cat monkey spanner
rabbit turtle root';
 
$lines = explode("\n",$lines);
foreach($lines as $line)
{
  echo substr($line,0,strpos($line,' '));
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply