views:

30

answers:

4

In PHP, what is the simplest way to return the portion of a string before the first occurrence of a specific character?

For example, if I have a string...

"The quick brown foxed jumped over the etc etc."

...and I am filtering for a space character (" "), the function would return "The"

Thanks!

+2  A: 

You could do this:

$string = 'The quick brown fox jumped over the lazy dog';
$substring = substr($string, 0, strpos($string, ' '));

But I like this better:

list($firstWord) = explode(' ', $string);
Jacob Relkin
Would that not throw errors? I thought link had to have a matching vairable set (or empty comma delimited) for the number of variables in the array you're exploding?
Alex
+2  A: 
$str = "The quick brown foxed jumped over the etc etc.";
$pattern = " ";
echo strstr($str, $pattern, true);

Prints 'The'.

tilman
I tried this code and got a warning: "Wrong parameter count for strstr()". The reason is that this code only works as of PHP 5.3.0. I'm using an earlier version of PHP.
matsolof
A: 

How about this:

$string = "The quick brown fox jumped over the etc etc.";

$splitter = " ";

$pieces = explode($splitter, $string);

echo $pieces[0];
tjk
+2  A: 

for googlers: strtok is better for that

echo strtok("The quick brown fox",  ' ');
stereofrog
To me this seems to be the best solution.
matsolof