0

I have been trying to capture only the numbers in this sentence so that it stays as follows:

Before:

 - 602,135 results  

After:

602135

I was testing the following: #\d+# But just select me 602

PS: I had already consulted in other posts but they could not solve my problem.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Kokox
  • 519
  • 1
  • 9
  • 24

3 Answers3

3

You can use preg_replace

Try this

$str = '- 602,135 results';
echo $result = preg_replace("/[^0-9]/","",$str);

Output - 602135

You can also use to get same output:-

$result = preg_replace('/\D/', '', $str);
shubham715
  • 3,324
  • 1
  • 17
  • 27
1

\D+ will do or equivalent to this is [^0-9]

will return digits only.

See it here: https://regex101.com/r/8CTgIm/1

[PHP] Use it like:

$re = '/\D+/';
$str = '- 602,135 results  ';
$subst = '';

$result = preg_replace($re, $subst, $str); //602135

echo "The result of the substitution is ".$result;
Ambrish Pathak
  • 3,813
  • 2
  • 15
  • 30
0

You don't have to use regex for this.
Not sure you actually gain something on not using regex here but here is one alternative method.

$str = " - 602,135 results  ";

Echo str_replace("-", "", filter_var($str, FILTER_SANITIZE_NUMBER_INT));

It uses filter_var to remove anything that is not number and that leaves -602135.
Then I use str_replace to remove the negative sign.

https://3v4l.org/iAVOB#output

Andreas
  • 23,610
  • 6
  • 30
  • 62