Satch3000
Satch3000

Reputation: 49404

PHP Get the first numbers on a string before text, ignore everything else

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?

Upvotes: 0

Views: 100

Answers (4)

user4707168
user4707168

Reputation:

Try this one:

preg_match_all('!\d+!', $theContent, $matches);
print_r( $matches);

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158090

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 ,.

Upvotes: 1

Eranda
Eranda

Reputation: 868

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;
    }
}

Upvotes: 0

Mr_Smile
Mr_Smile

Reputation: 29

If you want see this:

381

use

^(\d*)

But if you want see numbers with ","

381,000,000

use

^([\d,]*)

Upvotes: 1

Related Questions