4

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 first underscore.

example:

  14_hello_world = 14

Result is the number 14!

Thanks

  • Possible duplicate of [Get everything after a certain character](https://stackoverflow.com/questions/11405493/get-everything-after-a-certain-character) – kenorb Jul 23 '17 at 13:10

3 Answers3

10

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • but sometimes there is also a number after, like "14_hello_world22", would this work then? –  Feb 08 '10 at 10:51
  • You don't need to use substr(). Just use the function strstr(). It returns all characters from first occurrence of the needle (character in this case) till end of the string – DPC Jan 06 '15 at 10:12
  • 1
    @DPC "all characters from first occurrence of the needle (character in this case) till end of the string" is not what was asked for. If you want to use strstr you have to use the $beforeNeedle flag as show in my answer. – Gordon Jan 09 '15 at 22:12
  • @Gordon I know. I was just telling the functionality of that function. The readers should at least do some digging work on their own :P – DPC Jan 10 '15 at 07:19
5
preg_match('/^(\d+)/', $yourString, $matches);

$matches[1] will hold your value

RaYell
  • 69,610
  • 20
  • 126
  • 152
1

Simpler than a regex:

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

Outputs 14.

Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
  • The result can be checked for numerical value using is_numeric($split[0]), and you should set the limit to 2 in explode, because you do not need the rest, and check for $split not being an empty array. – Residuum Feb 08 '10 at 11:07