I’m having trouble with a string converted from a file resulting in the same as that string would behave if it was inputted directly:
Here is my test.html file:
<html>
<font class="editable">
This is editable section 1
</font>
<br><br><hr><br>
<font class="editable">
This is editable section 2
</font>
</html>
Here is my php file:
<?php
//RETURN ARRAY OF RESULTS FOUND BETWEEN START & END IN STRING
function returnStartEnd($string,$start,$end){
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
$out = array();
foreach($m[1] as $key => $value){
$type = explode('::',$value);
if(sizeof($type)>1){
if(!is_array($out[$type[0]]))
$out[$type[0]] = array();
$out[$type[0]][] = $type[1];
} else {
$out[] = $value;
}
}
return $out;
};
// RETURN FILE CONTENTS AS A STRING
function readFileToVar($file){
$fh = fopen($file,'r') or die($php_errormsg);
$html = fread($fh,filesize($file));
return $html;
fclose($fh) or die($php_errormsg);
};
$file = 'test.html';
$html = readFileToVar($file);
// OR
//$html = '<html> <font class="editable"> This is editable section 1 </font><br><br><hr><br><font class="editable"> This is editable section 2 </font> </html>';
$go = 'editable">';
$stop = '<';
$arrayOfEditables = returnStartEnd($html,$go,$stop);
echo "<br>Result:<br>";
var_dump($arrayOfEditables);
?>
Note the commented out $html. It is the same as what should(?) be returned from the test.html file. When trying to run the function returnStartEnd(), it works as expected on the commented out string, but not on the string created from file, returning an empty array.
What am I missing? Thanks.
Problem:
To me it is looking as if the regular expression is having trouble with the multiple lines. That appears to be the difference between the string that you passed in (bypassing the
file_get_contents()) and the contents of the loaded file.Solution:
Change the value of your regular express to allow for multiple lines:
This regular expression looks for the starting, and puts all values between that and the end into a character class. Then, at the end, I added the
mmodifier, which puts it into multi-line mode.According to my tests, both ways, this was what made it work for me: