68

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".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Travis
  • 2,011
  • 4
  • 22
  • 31
  • You might find [`s($str)->beforeFirst(' ')`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L389) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). – caw Jul 27 '16 at 01:07

6 Answers6

113

For googlers: strtok is better for that:

echo strtok("The quick brown fox", ' ');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user187291
  • 53,363
  • 19
  • 95
  • 127
  • 2
    Only downer about strtok, is if the token isn't found, it returns the whole string. – Progrock Aug 04 '16 at 15:46
  • 6
    Unless what you want is the entire string. Which is exactly what I needed. Thanks for making it explicit. – MikeSchinkel Aug 10 '16 at 10:07
  • Exactly what I needed (including the entire string thing). No need for any error handling as well. Thanks! – Source Matters Jan 03 '18 at 04:01
  • 1
    If your string starts with the 'token', it will be skipped; it won't return the empty string before the first 'token'; it will return the first nonempty part between 'tokens'. It will also return `false` (not an empty string) if you pass an empty string. A few gotchas. – Jake Jun 19 '20 at 00:35
91

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
  • 161,348
  • 33
  • 346
  • 320
  • 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 Sep 22 '10 at 08:16
  • 2
    in case you want to return the variable instead of assigning it `return array_shift(explode(' ', $string));` – E Ciotti Dec 11 '14 at 12:47
  • 2
    If the string(here a space) isn't found the first returns an empty string. The second returns the whole string. – Progrock Aug 04 '16 at 15:58
  • 6
    You can also use the `limit` parameter in [`explode(…)`](http://php.net/explode), so that `$string` isn't scanned any more than needed: `list($firstWord) = explode(' ', $string, 2);` – Socce Mar 16 '17 at 13:35
31

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.

powtac
  • 40,542
  • 28
  • 115
  • 170
Tilman Koester
  • 1,739
  • 2
  • 11
  • 25
  • 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 Sep 22 '10 at 14:09
  • 1
    If the needle isn't found it returns false. Which is what you'd expect. So personally this feels like the better answer. In many of the other answers you'd probably also need to check the string contains the token otherwise you get unpredictable results. Unless of course it's a given. – Progrock Aug 04 '16 at 15:54
  • Clean, and simple with good naming conventions for a clear understanding. – levi May 22 '17 at 21:15
  • This Answer should have more upvote since I use `strstr` to cut large text int half and `strstr` works bothways up and down :) ; – Salem Oct 20 '20 at 00:58
5

Use this:

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

$splitter = " ";

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

echo $pieces[0];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tjk
  • 194
  • 5
4

To sum up, there're four ways. Delimiter =:

  1. strstr($str, '=', true);
  2. strtok($str, '=');
  3. explode('=', $str)[0]; // Slowest
  4. substr($str, 0, strpos($str, '='));

This table illustrates output differences. Other outputs are pretty isomorphic.

+-------+----------------+----------+-------+----------------+-------+-------+
| $str  | "before=after" | "=after" | "="   | "no delimeter" | 1     | ""    |
+-------+----------------+----------+-------+----------------+-------+-------+
| 1.    | "before"       | ""       | ""    | false          | false | false |
| 2.    | "before"       | "after"  | false | "no delimeter" | "1"   | false |
| 3.    | "before"       | ""       | ""    | "no delimeter" | "1"   | ""    |
| 4.    | "before"       | ""       | ""    | ""             | ""    | ""    |

If troubles with multibyte appear then try for example mb_strstr:

mb_strstr($str, 'ζ', true);

Further notice: explode seems to be more straightforward, deals with multibyte and by passing third parameter returns both before and after delimeter

explode('ζ', $str, 2);
Hebe
  • 661
  • 1
  • 7
  • 13
  • The falsey ternary check is not always reliable if the substring before the needle is falsey. Gotcha: https://3v4l.org/AQXhc Also, `strpos($str, ' ')` might return `false` or offset `0`. That line of code is not reliable either. – mickmackusa Apr 27 '21 at 23:28
  • That seems like a real opportunity, then, for you to improve your answer with an [edit]. Please always be generous, reliable, and accurate when you share insights with researchers. – mickmackusa Apr 28 '21 at 20:51
  • hopefully improved now – Hebe Oct 20 '21 at 21:55
0

The strtok() function splits a string into smaller strings, for example:

$string = "The quick brown";
$token = strtok($string, " "); // Output: The

And if you don’t have spaces: print all characters

$string = "Thequickbrown";
$token = strtok($string, " "); // Output: Thequickbrown
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mamal
  • 1,791
  • 20
  • 14