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

Viewed 95516

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

6 Answers

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

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
Related