user2819389
user2819389

Reputation:

Get first word of every line

I need to get every first word of the lines in my $lines. So I'm doing an foreach on every line like this:

foreach ($lines as $n => $line) {

}

But then the next part, I need to grab only the first word. So I did this with exploding on a space like this:

$explode = explode(" ", $line);
echo $explode[0];

But this is very slow when I do it with many lines, is there a better and faster solution then using an explode() ?

Upvotes: 3

Views: 2093

Answers (6)

Dziad Borowy
Dziad Borowy

Reputation: 12579

You can also use explode with the limit:

explode(" ", $line, 1);

Although this is much faster than explode without the limit, it is not as fast as the substr() solution suggested by the user: Set Sail Media.

In my tests with 100K lines, every line having around 10K words:

explode       : 175s
explode+limit : 0s
substr()      : 0s

With 1M lines, every line having around 20K words:

explode       : too long :-)
explode+limit : 12s
substr()      : 0s

Upvotes: 0

devict
devict

Reputation: 609

You should try this :

list($firstWord) = explode(" ",trim($line));

see here

Upvotes: 0

dudemanbearpig
dudemanbearpig

Reputation: 1312

Use a regex. This should get the match before first space. (?:^|(?:\.\s))(\w+)

Upvotes: 0

Julian Schaefer
Julian Schaefer

Reputation: 37

Use the String Token function http://www.w3schools.com/php/func_string_strtok.asp

Upvotes: 1

UFL1138
UFL1138

Reputation: 642

Use strpos and substr. Get the index of the first space with strpos and then use that index as the end of your substr. That will save you exploding each line.

Upvotes: 3

Patrick Moore
Patrick Moore

Reputation: 13344

Yes!

$var = substr( $line, 0, strpos( $line, ' ' ) );

substr() trims a string using start position (0, the beginning) and length: http://php.net/manual/en/function.substr.php

We determine the length by using strpos() to find the first occurrence of the search phrase (in this case, a space): http://php.net/manual/en/function.strpos.php

Upvotes: 6

Related Questions