Home > Enterprise >  PHP preg_match with file_get_contents empty array match
PHP preg_match with file_get_contents empty array match

Time:12-03

I try to extract data with preg_match

<?php
$HTML   = '#a#TEXT#a#';
$REGEX  = '/#a#(.*?)#a#/';

preg_match($REGEX, $HTML, $MATCH);

print_r($MATCH);
var_dump($MATCH);
?>

This works fine. But if i try the same from a file with file_get_contents

This is the input file file.php: #a#TEXT#a#

<?php

$HTML   = file_get_contents("file.php");
$REGEX  = '/#a#(.*?)#a#/';

preg_match($REGEX, $HTML, $MATCH);

print_r($MATCH);
var_dump($MATCH);
?>

The array $MATCH is empty where is my error?

If the file is like: #a#TEXT#a# that works!

But if the file is in multiple lines (with breaks) like that::

#a#

TEXT

#a#

It doesn't work. How can I solve it ?

CodePudding user response:

Are you sure the file is being correctly read? Try a var_dump($HTML); after you load the file. If it's False, then the file could not be read

CodePudding user response:

This is the regex that help me to match any character across multiple lines :

$REGEX = '/#a#(.*?)#a#/s';

I put an s on my regex it works

  • Related