Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get numbers from string with PHP

Tags:

regex

php

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?

like image 639
Daniel Pairen Avatar asked Jun 28 '12 11:06

Daniel Pairen


People also ask

How to separate numbers in PHP?

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.

What is a numeric string PHP?

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]*)[\.

How do I check if a string contains only numbers in PHP?

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.

How do I cast an int in PHP?

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.


1 Answers

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

like image 170
DaveRandom Avatar answered Oct 12 '22 03:10

DaveRandom