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
Delete after first space?
Moderator: General Moderators
- jayshields
- DevNet Resident
- Posts: 1912
- Joined: Mon Aug 22, 2005 12:11 pm
- Location: Leeds/Manchester, England
Re: Delete after first space?
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.
Then you can implode that array with new lines or whatever.
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: Delete after first space?
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?
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.