Siddhu
Siddhu

Reputation: 241

How to get specific string value using REGEX in PHP

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"

Upvotes: 1

Views: 52

Answers (2)

Rendi Wahyudi Muliawan
Rendi Wahyudi Muliawan

Reputation: 284

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

Upvotes: 1

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

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)/

Upvotes: 1

Related Questions