tags:

views:

54

answers:

3

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

+4  A: 

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
Aaaargh, my eyes hurt! :)
Pekka
but sometimes there is also a number after, like "14_hello_world22", would this work then?
Camran
This is a horrific abuse of type casting, isn't it? The results may be predictable but still!
Pekka
@camran yes. It will work even then.
Gordon
@Pekka unless you explain why you consider this an abuse when the outcome of this is well documented and predictable, I see no reason to agree :) Regex and Exploding is a way worse way to solve this imho.
Gordon
@Gordon: Aarrrgh. It just doesn't feel right to me at all. But well, it's defined and works, and the OP hath spoken :) To me, the proper (but ugly-looking) way would be finding the first occurrence of `_`, and getting a `substr` of everything before that.
Pekka
+5  A: 
preg_match('/^(\d+)/', $yourString, $matches);

$matches[1] will hold your value

RaYell
Are you sure about `[1]`? I'd say it would be `[0]`
Robin
I'm sure. `[0]` will hold the whole matched string, while `[1]` will have first group value (parenthesis)
RaYell
+1  A: 

Simpler than a regex:

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

Outputs 14.

Max Shawabkeh
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