1

header.php file

<?php
 echo 'this is example '.$adv['name'].' , this is another.....';

main.php file

<?php

if(preg_match('/$adv[(.*?)]/',file_get_contents('header.php'),$itext)){
    echo $itext[1].'';
}

show empty

2 Answers2

2

this regular expression will work

/\$adv\[(.*?)\]/

You need to escape symbols $,[,] using \ before them since they have special meaning in regular expressions

evgpisarchik
  • 452
  • 5
  • 9
1

Here is a more efficient solution:

Pattern (Demo):

/\$adv\[\K[^]]*?(?=\])/

PHP Implementation:

if(preg_match('/\$adv\[\K[^]]*?(?=\])/','this is example $adv[name]',$itext)){
    echo $itext[0];
}

Output for $itext:

name

Notice that by using \K to replace the capture group, the targeted string is returned in the "full string" match which effectively reduces the output array by 50%.

You can see the demo link for explanation on individual pieces of the pattern, but basically it matches $adv[ then resets the matching point, matches all characters between the square brackets, then does a positive lookahead for a closing square bracket which will not be included in the returned match.

Regardless of if you want to match different variable names you could use: /\$[^[]*?\[\K[^]]*?(?=\])/. This will accommodate adv or any other substring that follows the dollar sign. By using Negated Character Classes like [^]] instead of . to match unlimited characters, the regex pattern performs more efficiently.

If adv is not a determining component of your input strings, I would use /\$[^[]*?\[\K[^]]*?(?=\])/ because it will be the most efficient.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136