get number in front of 'underscore' with php

前端 未结 3 1661
轮回少年
轮回少年 2021-01-13 15:22

I have this:

15_some_text_or_numbers;

I want to get whats in front of the first underscore. There is always a letter directly after the fir

相关标签:
3条回答
  • 2021-01-13 15:43

    Simpler than a regex:

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

    Outputs 14.

    0 讨论(0)
  • 2021-01-13 15:46

    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.

    0 讨论(0)
  • 2021-01-13 15:52
    preg_match('/^(\d+)/', $yourString, $matches);
    

    $matches[1] will hold your value

    0 讨论(0)
提交回复
热议问题