user7700973
user7700973

Reputation:

php preg_match() not working, find a var

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

Upvotes: 1

Views: 287

Answers (2)

mickmackusa
mickmackusa

Reputation: 47991

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.

Upvotes: 1

evgpisarchik
evgpisarchik

Reputation: 460

this regular expression will work

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

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

Upvotes: 2

Related Questions