微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP 按行读取文件内容并截取每行指定字符串之间的内容组成数组

public function get_file_content()
{
// 连接文件并读取内容 dirname(__FILE__): 得到当前文件地址
$contents = file_get_contents(dirname(__FILE__).'/time.PHP');
// 获取文件编码方式
$encoding = mb_detect_encoding($contents, array('GB2312', 'GBK', 'UTF-16', 'UCS-2', 'UTF-8', 'BIG5', 'ASCII'));
// 修改编码为utf-8 防止乱码
$contents = iconv($encoding, 'UTF-8', $contents);
// 按行分割 返回一维数组
$contents = explode("\n", $contents);
// 组织数据 &符:可直接对$contents赋值
foreach ($contents as &$info)
{
$info= array(
'zone' => $this->get_sub_str('"', '">', $info),
'time_differ' => $this->get_sub_str('(', ')', $info),
'title_en' => $this->get_sub_str(') ', '</option>', $info),
);
}
// 打印查看结果
var_dump($contents);die;
}

// 截取指定两个字符串之间的字符串
private function get_sub_str($start,$end,$str)
{
   // 得到要截取字符串的开始位置 mb_strpos(): 得到字符串首次出现的位置
$start = mb_strpos($str,$start) + mb_strlen($start);
   // 得到要截取字符串的长度
$length = mb_strpos($str,$end) - $start;
   // 截取字符串
return mb_substr($str,$start,$length);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐