PHP regex delete everything after character

So, I saw a couple of articles that are a little deeper, so I'm not sure what to remove from the regex expressions that they make.

I basically got this

foo: bar to anotherfoo: bar; seg98y34g.? sdebvw h segvu (everything goes really)

I need a PHP regular expression to remove EVERYTHING after a colon. the first part can be of any length (but it never contains a colon, so in both cases above I get

foo and anotherfoo

making something like this terrifying psuedo-code example

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

EDIT

after posting this question, will explode() work reliably enough? Sort of

 $pieces = explode(':', 'foo:bar') $newstring = $pieces[0]; 
+6
source share
6 answers

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

+20
source

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

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

A bit more concise than other examples:

 current(explode(':', $string)); 
+3
source

You can use RegEx, which 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); 
+2
source

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

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

Why do you want to use regex?

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

Source: https://habr.com/ru/post/926783/


All Articles