PHP Regex删除字符后的所有内容 [英] PHP Regex to remove everything after a character
问题描述
所以我看过几篇文章,内容太深了,所以我不确定要从它们做的正则表达式中删除什么.
我基本上已经知道了
foo:bar 一直到 otherfoo:bar; seg98y34g.?sdebvw h segvu (一切正常)
我需要一个PHP正则表达式来删除冒号之后的所有内容.第一部分可以是任何长度(但绝不包含冒号.因此,在上述两种情况下,我最终都会得到
foo 和另一个foo
做了类似伪代码这样可怕的例子之后
$string = 'foo:bar';
$newstring = regex_to_remove_everything_after_":"($string);
编辑
发布此内容后,explode()
是否足够可靠地工作?像
$pieces = explode(':', 'foo:bar')
$newstring = $pieces[0];
explode
可以您想要的东西,但是您可以使用 current
一步一步完成.. >
$beforeColon = current(explode(':', $string));
我不会在这里使用正则表达式(涉及幕后的一些工作以进行相对简单的操作),也不会使用 substr
两次遍历字符串).最重要的是,这为读取代码的人提供了立即的提示,啊,是的,这就是作者正在尝试做的!"而不是等等,又发生了什么?"
唯一的例外是,如果您碰巧知道该字符串过长:我不会explode
1 Gb文件.相反:
$beforeColon = substr($string, 0, strpos($string,':'));
我也觉得substr
不太容易阅读:在current(explode
中,您可以立即看到定界符,而无需额外的函数调用,并且变量只有一个事件(这使得它不太容易被人类使用)错误).基本上,我将current(explode
读为我正在此字符串之前发生任何事情的第一个事件",而与substr
相对,它是我正在从0位置开始直到该字符串的子字符串." >
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."
这篇关于PHP Regex删除字符后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!