Get number before underscore with php

I have it:

15_some_text_or_numbers; 

I want to get something before the first underline. There is always a letter immediately after the first underline.

Example:

  14_hello_world = 14 

The result is the number 14!

thanks

+4
source share
3 answers

If there is always a front number, you can use

 echo (int) '14_hello_world'; 

See the entry in Converting Strings to Integers in the PHP Manual

Here is the version without typecasting:

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

Note that this will not return anything if the underscore is not found. If found, the return value will be a string, while the result with the drive will be integer (not so important). If you want the whole row to be returned when there is no underscore, you can use

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

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

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

Note: As traits from a string to an integer in PHP, predictable behavior should be clearly defined and such behavior follows the Unix rules of "own strtod for mixed strings, I do not see how the first approach abuses traits.

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

$matches[1] will hold your value

+5
source

Easier than regex:

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

Outputs 14.

+1
source

Source: https://habr.com/ru/post/1300612/


All Articles