Page 1 of 1

Delete after first space?

Posted: Fri Sep 12, 2008 8:36 am
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

Re: Delete after first space?

Posted: Fri Sep 12, 2008 9:14 am
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.

Re: Delete after first space?

Posted: Fri Sep 12, 2008 9:27 am
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);

Re: Delete after first space?

Posted: Fri Sep 12, 2008 10:01 am
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,' '));
}