开发者

get number in front of 'underscore' with php

开发者 https://www.devze.com 2022-12-20 00:13 出处:网络
I have this: 15_some_text_or_numbers; I want to get what开发者_开发百科s in front of the first underscore.

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!

Thanks


If there is always a number in front, you can use

echo (int) '14_hello_world';

See the entry on String conversion to integers in the PHP manual

Here is a version without typecasting:

$str = '14_hello_1world_12';
echo substr($str, 0, strpos($str, '_'));

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

$str = '14_hello_1world_12';
echo str_replace(strstr($str, '_'), '', $str);

As of PHP5.3 you can also use strstr with $before_needle set to true

echo strstr('14_hello_1world_12', '_', true);

Note: 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.


preg_match('/^(\d+)/', $yourString, $matches);

$matches[1] will hold your value


Simpler than a regex:

$x = '14_hello_world';
$split = explode('_', $x);
echo $split[0];

Outputs 14.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号