Sameer K
Sameer K

Reputation: 799

Capturing text between square brackets after a substring in PHP

I have string like below which is coming from DB.

$temp=Array(true);
if($x[211] != 15)
    $temp[] = 211;
if($x[224] != 1)
    $temp[] = 211;
if(sizeof($temp)>1) {
    $temp[0]=false;
}
return $temp;

I need to find all the values inside square brackets followed by $x variable. I.e 211 and 224 .

I tried below code which i found in this website as an answer, but it returns all the values in square bracket including the one followed $temp variable.

preg_match_all("/\[(.*?)\]/", $text, $matches);
print_r($matches[1]);

Please let me know how can i get this desired results ?

Upvotes: 0

Views: 1476

Answers (2)

Harpreet Singh
Harpreet Singh

Reputation: 2671

RegEx

(?<=\$x\[).*(?=\])

Demo

$re = "/(?<=\$x\[).*(?=\])/"; 
$str = "Sample String"; 

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

Explanation

  • LookBehind - Matching pattern should come after $x[ --- (?<=\$x\[). If pattern to be matched is XYZ then behind XYZ $X should exist.

  • .* match all after the last matching pattern

  • LookAhead - (?=\]) - Match all untill ]

Upvotes: 1

bloodyKnuckles
bloodyKnuckles

Reputation: 12089

Since PHP interpolates variables (variables start with dollar signs) inside double quoted strings, putting the preg_match_all regex in a single quoted string prevents that. Although the "$" is still escaped in the regex since it's a regex anchor character.

In this case /x\[(.*?)\]/ also works, but I think the more precise you can be the better.

$text = '
$temp=Array(true);
if($x[211] != 15)
    $temp[] = 211;
if($x[224] != 1)
    $temp[] = 211;
if(sizeof($temp)>1) {
    $temp[0]=false;
}
return $temp;
';

preg_match_all('/\$x\[(.*?)\]/', $text, $matches);
print_r($matches[1]);

Output:

Array ( [0] => 211 [1] => 224 )

Upvotes: 0

Related Questions