drew schmaltz
drew schmaltz

Reputation: 1584

Regular Expressions: Numeric Value before Occurrence PHP

Given the string:

100,000 this is some text 12,000 this is text I want to match.

I need a regular expression that matches 12,000 based on matching

text I want to match

So, we can get a position with:

strpos($haystack, 'text I want to match');

Then, I guess we could use a regular expression to look backwards:

But, this is where I need help.

Upvotes: 0

Views: 54

Answers (3)

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Another solution:

$re = "/([\\d,]+)(?=\\D*text I want to match)/";
$str = "100,000 this is some text 12,000 this is text I want to match.";

preg_match($re, $str, $matches);

Live demo

Upvotes: 0

Ruben Kazumov
Ruben Kazumov

Reputation: 3872

It is simple:

/ ([0-9,]+) this is text I want to match\.$/

Demo:

http://sandbox.onlinephpfunctions.com/code/b288ca9a322c7a5b54c6490334540ab142b6a979

Upvotes: 2

hwnd
hwnd

Reputation: 70722

If you know that the digits will always precede the based context you want to match ...

preg_match('/([\d,]+)\D*text I want to match/', $str, $match);
var_dump($match[1]);

Upvotes: 2

Related Questions