PHP substr 在某个字符之后,一个 substr + strpos 优雅的解决方案?
假设我想返回来自
$source_str = "Tuex helo babe"
的某个针字符 'x'
之后的所有字符。
通常我会这样做:
if( ($x_pos = strpos($source_str, 'x')) !== FALSE )
$source_str = substr($source_str, $x_pos + 1);
你知道更好/更智能(更优雅的方式)来做到这一点吗?
如果不使用正则表达式,那不会使它更优雅,而且可能还会更慢。
不幸的是我们不能这样做:
$source_str = substr(source_str, strpos(source_str, 'x') + 1);
因为当找不到 'x'
时,strpos
返回 FALSE
(而不是 -1
就像 JS 中一样)。 FALSE
将计算为零,并且第一个字符将始终被切断。
谢谢,
let's say I want to return all chars after some needle char 'x'
from:
$source_str = "Tuex helo babe"
.
Normally I would do this:
if( ($x_pos = strpos($source_str, 'x')) !== FALSE )
$source_str = substr($source_str, $x_pos + 1);
Do you know a better/smarter (more elegant way) to do this?
Without using regexp that would not make it more elegant and probably also slower.
Unfortunately we can not do:
$source_str = substr(source_str, strpos(source_str, 'x') + 1);
Because when 'x'
is not found strpos
returns FALSE
(and not -1
like in JS).FALSE
would evaluate to zero, and 1st char would be always cut off.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在
$item
末尾附加一个 '-',这样它总是在 '-' 之前返回字符串,即使$item
不包含 '-',因为 strpos 默认返回'-' 第一次出现的位置。Append a '-' at the end of
$item
so it always returns string before '-' even$item
doesn't contain '-', because strpos by default returns the position of first occurrence of '-'.您的第一种方法很好:检查
x
是否包含在strpos
中,如果包含,则使用substr
在其后面获取任何内容。但您也可以使用
strstr
:但因为这会返回以 开头的子字符串 < code>x,使用
substr
来获取x
之后的部分:但这要复杂得多。因此,请改用
strpos
方法。Your first approach is fine: Check whether
x
is contained withstrpos
and if so get anything after it withsubstr
.But you could also use
strstr
:But as this returns the substring beginning with
x
, usesubstr
to get the part afterx
:But this is far more complicated. So use your
strpos
approach instead.正则表达式会让它变得更加优雅:
但你总是可以尝试这个:
Regexes would make it a lot more elegant:
But you can always try this:
不太优雅,但开头没有
x
:Less elegant, but without
x
in the beginning:我只需要这个,并且为了好玩而努力将其保留在一行上:
ltrim(strstr($source_str, $needle = "x") ?: $source_str, $needle);
三元运算符
在 5.3 中进行了修改,以使其能够工作。注意。
ltrim
将修剪字符串开头的多个匹配字符。I needed just this, and striving to keep it on one line for fun came up with this:
ltrim(strstr($source_str, $needle = "x") ?: $source_str, $needle);
The
ternary operator
was adapted in 5.3 to allow this to work.NB.
ltrim
will trim multiple matching characters at the start of the string.