I have strings:
$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';
How can I find the numeric digits in these strings?
Maybe with function:
function numbers($string){
// ???
$first = ?;
$second = ?;
}
For example:
function numbers($one){
// ???
$first = 4;
$second = 5;
}
function numbers($two){
// ???
$first = 2;
$second = NULL;
}
Best way for this maybe is regex, but how can I use this for my example? Maybe without regex?
PHP - Function split() The optional input parameter limit is used to signify the number of elements into which the string should be divided, starting from the left end of the string and working rightward.
Numeric strings ¶ A PHP string is considered numeric if it can be interpreted as an int or a float. Formally as of PHP 8.0.0: WHITESPACES \s* LNUM [0-9]+ DNUM ([0-9]*)[\.
The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.
You can use (int) or (integer) to cast a variable to integer, use (float) , (double) or (real) to cast a variable to float. Similarly, you can use the (string) to cast a variable to string, and so on. The PHP gettype() function returns "double" in case of a float for historical reasons.
You can use regular expressions for this. The \d
escape sequence will match all digits in the subject string.
For example:
<?php
function get_numerics ($str) {
preg_match_all('/\d+/', $str, $matches);
return $matches[0];
}
$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';
print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));
https://3v4l.org/DiDBL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With