phpstringtext-extractiontruncation

Get number in front of first occurrence of a character


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.


Solution

  • 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.