1

I have a string content.

$string = "FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley.";

Here I want to take a specific string

"then he ate some radishes"

How can I do it with REGEX? I want it in REGEX only

I want to pass just 2 parameters like 
1. then 
2. radishes

so finally I want output like "then he ate some radishes"

2 Answers 2

1

You can use /(?<=then).*(?=radishes)/ to get everything between then and radishes.

$re = '/(?<=then).*(?=radishes)/';
$str = 'FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley.';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);

Break down:

  • Positive Lookbehind (?<=then): Assert that the Regex below matches then matches the characters then literally (case sensitive)
  • .* matches any character (except for line terminators)
  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • Positive Lookahead (?=radishes): Assert that the Regex below matches radishes matches the characters radishes literally (case sensitive)

The requirement in OP is to match everything including then and radishes, so you can use /then.*radishes/ in place of /(?<=then).*(?=radishes)/

To make the regex non greedy, you should go for /then.*?radishes/ and /(?<=then).*?(?=radishes)/

Sign up to request clarification or add additional context in comments.

2 Comments

Note that the desired output is "then he ate some radishes", so the lookahead and lookbehind are unnecessary.
You can use /then.*radishes/ to match everything.
1

Just simply use this

$string = "FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley.";

preg_match("/then(.*?)radishes/", $string, $matches);

echo $matches[0];

You can practice in https://regexr.com/

My demo see here https://regexr.com/3mj4v

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.