xpedobearx
xpedobearx

Reputation: 817

How to pick up all numbers from string

I have a string that looks like abc,5,7 from which I want to get the numbers.

I've come up with this:

^(?<prefix>[a-z]+)(,(?<num1>\d+?))?(,(?<num2>\d+?))?$#i

but it will only work with 2 numbers, and my string has a variable number of numbers. I don't know how to change the regex to account for that. Help please

Upvotes: 2

Views: 124

Answers (3)

Vigneswaran S
Vigneswaran S

Reputation: 2094

try this . very simple use preg_replace('/[A-Za-z,]+/', '', $str);// removes alphabets from the string and comma

<?php
$str="bab,4,6,74,3668,343";
$number = preg_replace('/[A-Za-z,]+/', '', $str);// removes alphabets from the string and comma
echo $number;// your expected output 
?>

expected output

46743668343

Upvotes: 1

Rick Su
Rick Su

Reputation: 16440

explode with comma , is the easiest way.

but if you insist to do it with regexp

here is how

$reg = '#,(\d+)#';

$text = 'abc,5,7,9';

preg_match_all($reg, $text, $m);

print_r($m[1]);

/* Output
Array
(
    [0] => 5
    [1] => 7
    [2] => 9
)
*/

Upvotes: 1

Lemon Kazi
Lemon Kazi

Reputation: 3311

You can try this

<?php
$string = "abc,5,7";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
?>

Also you can Use this regular expression !\d!

<?php
$string = "abc,5,7";
preg_match_all('!\d!', $string, $matches);
echo (int)implode('',$matches[0]);

enter image description here

Upvotes: 2

Related Questions