0

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.

1
  • Wouldn't you match a number followed by what you want to match? Like ([\d,]+) this is text I want to match. Commented Feb 9, 2015 at 22:58

3 Answers 3

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

2

It is simple:

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

Demo:

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

1 Comment

This was a great quick answer but a more complete answer that allowed more of the flexibility I needed was offered.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.