regex - How to regexp PHP looking for numbers in string


Keywords:php 


Question: 

I've problem with regexp and I'm looking solutions for this problem.

I need to find in text numbers where is more than 3 digits, but I need to omit when number have on beginning/last $ char.

Example:

Lorem ipsum dolor 32 sit 32181527 amet, consectetur adipiscing $18312.90, 2432417$.

On results I want to get only this number 32181527.

I know how to get numbers but I can't omit when is $ occurs.

[0-9]{3,}

1 Answer: 

Using negative look-behind, negative look-ahead assertions, you can limit match that is not preceded / followed by specific pattern:

$text = "Lorem ipsum dolor 32 sit 32181527 amet, consectetur adipiscing $18312.90, 2432417$.";
preg_match_all('/(?<![0-9$])[0-9]{3,}(?![0-9$])/', $text, $matches);
// match 3+ digits which is not preceded by digits/$.
// also the digits should not be followed by digits/$.
print_r($matches);

output:

Array
(
    [0] => Array
        (
            [0] => 32181527
        )

)