Home > Software design >  Why no matches regex?
Why no matches regex?

Time:07-17

I created regex, using regex101 and it shows, that is all ok. https://regex101.com/r/gLF7yl/1

But when I use it in my code, it doesn`t work.

Here is my code:

foreach ($varsArray as $var) {
            var_dump($var); // $_['heading_title'] = 'Запрашиваемая страница не найдена!';
            $regex = "/^\$_\['([a-z|_] )'\]  = '(. )';$/u";
            preg_match_all($regex, $var, $matches); 
            var_dump($matches); // array(3) { [0]=> array(0) { } [1]=> array(0) { } [2]=> array(0) { } }
        }

CodePudding user response:

The reason this is happening is because of the escaping required when you have a string that contains a variable instantiation. Your strings actually look like this:

\$_['heading_title'] = 'Запрашиваемая страница не найдена!';

So you need to update your regex to include the added slash:

$regex = "/^\\\$_\['([a-z|_] )'\]  = '(. )';$/u";

Example:

$var = "\$_['heading_title'] = 'Запрашиваемая страница не найдена!';";
var_dump($var);
$regex = "/^\\\$_\['([a-z|_] )'\]  = '(. )';$/u";
preg_match_all($regex, $var, $matches); 
var_dump($matches);

Results in:

string(89) "$_['heading_title'] = 'Запрашиваемая страница не найдена!';"
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(89) "$_['heading_title'] = 'Запрашиваемая страница не найдена!';"
  }
  [1]=>
  array(1) {
    [0]=>
    string(13) "heading_title"
  }
  [2]=>
  array(1) {
    [0]=>
    string(64) "Запрашиваемая страница не найдена!"
  }
}

Notice how the first var_dump of the string by itself doesn't include the extra slash.

  • Related