获取字符第一次出现前面的数字
我有这个:
15_some_text_or_numbers;
我想获取第一个下划线前面的内容。 第一个下划线后面总是有一个字母。
示例:
14_hello_world = 14
结果是数字14
。
I have this:
15_some_text_or_numbers;
I want to get what's in front of the first underscore.
There is always a letter directly after the first underscore.
Example:
14_hello_world = 14
Result is the number 14
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果前面总是一个数字,您可以使用
查看PHP 手册中的字符串到整数的转换
这是一个没有类型转换的版本:
请注意,如果没有找到下划线,这将不会返回任何内容。如果找到,返回值将是一个字符串,而类型转换的结果将是一个整数(但这并不重要)。如果您希望在不存在下划线时返回整个字符串,则可以使用
从 PHP5.3 开始,您还可以使用
strstr
并将$before_needle
设置为 true注意:由于 PHP 中从字符串到整数的类型转换遵循明确定义且可预测的行为,并且此行为遵循 Unix 自己的
strtod
对于混合字符串的规则,我不明白第一个如何方法是滥用类型转换。If there is always a number in front, you can use
See the entry on String conversion to integers in the PHP manual
Here is a version without typecasting:
Note that this will return nothing, if no underscore is found. If found, the return value will be a string, whereas the typecasted result will be an integer (not that it would matter much). If you'd rather want the entire string to be returned when no underscore exists, you can use
As of PHP5.3 you can also use
strstr
with$before_needle
set to trueNote: As typecasting from string to integer in PHP follows a well defined and predictable behavior and this behavior follows the rules of Unix' own
strtod
for mixed strings, I don't see how the first approach is abusing typecasting.$matches[1]
将保存您的值$matches[1]
will hold your value比正则表达式更简单:
输出 14。
Simpler than a regex:
Outputs 14.
演示
我更喜欢
sscanf()
因为它的行为很明确 - - 它隔离前导数字并将返回值转换为整数。或者
转换为整数是一种隐式操作,我有时也在应用程序中使用它。与
sscanf()
一样,此技术也会保留数字前面的负号(作为附带考虑)。preg_replace()
是一种直接的方法并且可靠,但是输出值不会被转换为整数,捕获负整数将需要模式调整,并且您的开发团队将需要对正则表达式。preg_match()
需要一个非常简单的模式,但会在访问所需的字符串之前创建一个数组。必须调整负整数。以下技术依赖于紧随所需值之后的已知字符的存在。如果没有静态特征可以利用,下面的内容就不适合了。
还有
还有
Demos
I prefer
sscanf()
because it is explicit in its behavior -- it isolates the leading digits and casts the returned value as an integer.Or
Casting to an integer is an implicit operation which I also sometimes use in applications. Like
sscanf()
, this technique will retain the negative sign before a number as well (as a fringe consideration).preg_replace()
is a direct approach and reliable, but the output value will not be cast as an integer, capturing negative integers will require pattern adjustment, and your dev team will need a minimum understanding of regex.preg_match()
requires a very simple pattern, but creates an array before the desired string can be accessed. Negative integers must be adjusted for.the following techniques rely on the existence of a known character immediately after the desired value. If there is no static character to leverage, the following will be unsuitable.
And
And