explode will do what you ask for, but you can do it one step at a time using current .
$beforeColon = current(explode(':', $string));
I would not use a regex here (which requires some work behind the scenes for a relatively simple action), and I would not use strpos with substr (since this could effectively cross the string twice). Most importantly, it gives the person who reads the code immediately: "Ah, yes, this is what the author is trying to do!" rather than "Wait, what's happening again?"
The only exception is if you know that the line is too long: I would not become an explode 1 GB file. Instead of this:
$beforeColon = substr($string, 0, strpos($string,':'));
I also feel that substr not so easy to read: in current(explode you can immediately see the delimiter without additional function calls, and there is only one case of the variable (which makes it less prone to human error). Basically I read current(explode as "I accept the first case of anything before this line," rather than substr , and this is "I get a substring starting at position 0 and continuing to this line."
source share