0

I have a string and I'm trying to get only the numbers, which is currently working.

My problem is that I just want to get the numbers before the word results and ignore everything else.

Here's an example string:

echo '381,000,000 results 1. something here 12345566778898776655444';

$theContent = preg_replace('/\D/', '', $theContent);
echo $theContent;

How can I just get the numbers before the word results and ignore results and everything after that?

Satch3000
  • 40,202
  • 83
  • 203
  • 337
  • 1
    Given that commas aren't part of a number, but merely a way of formatting a number for display purposes, you'll have to make allowances for that – Mark Baker Mar 24 '15 at 11:34
  • What would be the expected output? – Rizier123 Mar 24 '15 at 11:34
  • Go through this [answer](http://stackoverflow.com/questions/4246077/matching-numbers-with-regular-expressions-only-digits-and-commas/4247184#4247184) and just use `preg_match()` with a lookahead `(?=\s+results\b)` – HamZa Mar 24 '15 at 11:36
  • 1
    `$theContent = '381,000,000 results 1. something here 12345566778898776655444'; echo $theContent, PHP_EOL; $theContent = preg_match('/\d+/', preg_replace('/\,/', '', $theContent), $matches); echo $matches[0]; ` – Mark Baker Mar 24 '15 at 11:42
  • That worked! Thanks :P – Satch3000 Mar 24 '15 at 11:50

4 Answers4

1

If you want see this:

381

use

^(\d*)

But if you want see numbers with ","

381,000,000

use

^([\d,]*)

Mr_Smile
  • 29
  • 4
1

I would first match all the numbers at start concatenated by , and explode() them by , afterwards:

$string = '381,000,000 results 1. something here 12345566778898776655444';
$pattern = '/((^|,)([\d]+))*/';

preg_match($pattern, $string, $matches);
$numbers = explode(',', $matches[0]);

var_dump($numbers);

IMO this is the most stable solution.

About the regex pattern: It matches the sequence start of the line or a , followed by one ore more numeric characters multiple times. It uses capturing groups () to separate the numbers from the ,.

hek2mgl
  • 133,888
  • 21
  • 210
  • 235
0

You can get number from this:

$theContent = '381,000,000 results 1. something here 12345566778898776655444';

$array = explode(" ", $theContent);

$wantedArray = [];

foreach ($array as $item) {
    if (is_numeric(str_replace(",", "", $item))) {
        $wantedArray[] = $item;
    }
}
Eranda
  • 754
  • 1
  • 9
  • 23
0

Try this one:

preg_match_all('!\d+!', $theContent, $matches);
print_r( $matches);
smottt
  • 3,091
  • 11
  • 37
  • 42