【发布时间】:2012-11-29 04:57:54
【问题描述】:
我在处理从文件转换的字符串时遇到问题,结果与直接输入该字符串的行为相同:
这是我的 test.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>
这是我的 php 文件:
<?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);
?>
注意注释掉的$html。它与 test.html 文件中应该(?)返回的内容相同。尝试运行函数 returnStartEnd() 时,它在注释掉的字符串上按预期工作,但对从文件创建的字符串不起作用,返回一个空数组。
我错过了什么?谢谢。
【问题讨论】:
-
为什么不直接使用
file_get_contents?这简单得多。 -
需要注意的一点是,在您调用 return 之后,您正在调用
fclose($fh)。fclose()永远不会发生。 -
谢谢,我正在使用我在堆栈或 php.net 上找到的一段脚本。 @AlvinWong 我已经多次尝试使用 file_get_contents 来实现这种功能,但永远无法让字符串表现得像我预期的那样。你能发布一个工作示例吗?
-
什么?就像
$html = file_get_contents($file)一样简单 -
@AlvinWong 这对我来说永远不起作用。 (我承认我是一个 php 新手)当字符串应该返回一个 2 的数组时,它也返回一个 0 的数组
标签: php string preg-match fread