Return the portion of a string before the first occurrence of a character in php

For googlers: strtok is better for that:

echo strtok("The quick brown fox", ' ');

strstr() Find the first occurrence of a string. Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

Third param: If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

$haystack  = 'The quick brown foxed jumped over the etc etc.';
$needle    = ' ';
echo strstr($haystack, $needle, true);

Prints The.


Use this:

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

$splitter = " ";

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

echo $pieces[0];

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);

Tags:

Php

String