Reputation:
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
.
Upvotes: 3
Views: 3671
Reputation: 48011
I prefer sscanf()
because it is explicit in its behavior -- it isolates the leading digits and casts the returned value as an integer.
echo sscanf($string, '%d')[0];
Or
sscanf($string, '%d', $integer);
echo $integer;
Casting to an integer is an implicit operation which I also sometimes use in applications. Like sscanf()
, this technique will retain the negative sign before a number as well (as a fringe consideration).
echo (int) $string;
preg_replace()
is a direct approach and reliable, but the output value will not be cast as an integer, capturing negative integers will require pattern adjustment, and your dev team will need a minimum understanding of regex.
echo preg_replace('/^\d+\K.*/', '', $string);
preg_match()
requires a very simple pattern, but creates an array before the desired string can be accessed. Negative integers must be adjusted for.
echo preg_match('/^\d+/', $string, $m) ? $m[0] : null;
the following techniques rely on the existence of a known character immediately after the desired value. If there is no static character to leverage, the following will be unsuitable.
echo strstr($string . '_', '_', true); // append an underscore to the input if not guaranteed
And
echo explode('_', $string, 2)[0]; // the limit parameter prevents needeless explosions
And
echo strtok($string, '_');
Upvotes: 0
Reputation: 317147
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.
Upvotes: 10
Reputation: 38643
Simpler than a regex:
$x = '14_hello_world';
$split = explode('_', $x);
echo $split[0];
Outputs 14.
Upvotes: 1
Reputation: 70444
preg_match('/^(\d+)/', $yourString, $matches);
$matches[1]
will hold your value
Upvotes: 5