简体   繁体   中英

PHP Regex to remove everything after a character

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

EDIT

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

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

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

比其他示例更简洁:

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

您可以使用m.buettner编写的RegEx,但他的示例将返回':'之前的所有内容,如果您希望':'之后的所有内容,只需使用$ 2而不是$ 1:

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

You could 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;
?>

为什么要使用正则表达式?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM