Home » Php » PHP Regex to remove everything after a character

PHP Regex to remove everything after a character

Posted by: admin July 12, 2020 Leave a comment


So I’ve seen a couple articles that go a little too deep, so I’m not sure what to remove from the regex statements they make.

I’ve basically got this

foo:bar all the way to anotherfoo:bar;seg98y34g.?sdebvw h segvu (anything goes really)

I need a PHP regex to remove EVERYTHING after the colon. the first part can be any length (but it never contains a colon. so in both cases above I’d end up with

foo and anotherfoo

after doing something like this horrendous example of psuedo-code

$string = 'foo:bar';
$newstring = regex_to_remove_everything_after_":"($string);


after posting this, would an explode() work reliably enough? Something like

$pieces = explode(':', 'foo:bar') 
$newstring = $pieces[0];
How to&Answers:

explode would do what you’re asking for, but you can make it one step by using current.

$beforeColon = current(explode(':', $string));

I would not use a regex here (that involves some work behind the scenes for a relatively simple action), nor would I use strpos with substr (as that would, effectively, be traversing the string twice). Most importantly, this provides the person who reads the code with an immediate, “Ah, yes, that is what the author is trying to do!” instead of, “Wait, what is happening again?”

The only exception to that is if you happen to know that the string is excessively long: I would not explode a 1 Gb file. Instead:

$beforeColon = substr($string, 0, strpos($string,':'));

I also feel substr isn’t quite as easy to read: in current(explode you can see the delimiter immediately with no extra function calls and there is only one incident of the variable (which makes it less prone to human errors). Basically I read current(explode as “I am taking the first incident of anything prior to this string” as opposed to substr, which is “I am getting a substring starting at the 0 position and continuing until this string.”


Your explode solution does the trick. If you really want to use regexes for some reason, you could simply do this:

$newstring = preg_replace("/(.*?):(.*)/", "$1", $string);


A bit more succinct than other examples:

current(explode(':', $string));


You can use RegEx that m.buettner wrote, but his example returns everything BEFORE ‘:’, if you want everything after ‘:’ just use $2 instead of $1:

$newstring = preg_replace("/(.*?):(.*)/", "$2", $string);


You could use something like the following. demo: http://codepad.org/bUXKN4el

  $s = 'anotherfoo:bar;seg98y34g.?sdebvw h segvu';
  $result = array_shift(explode(':', $s));
  echo $result;


Why do you want to use a regex?

list($beforeColon) = explode(':', $string);