【问题标题】:How can get from file just specific data using file_get_contents and preg_match如何使用 file_get_contents 和 preg_match 从文件中获取特定数据
【发布时间】:2014-01-07 19:14:53
【问题描述】:

我想从 smb.conf 获取有关共享文件夹 [share] 和路径“path =”的数据,但我想跳过行;和 // 感谢您的回答。

示例 smb.conf

;[profiles]
;   comment = Users profiles
;   path = /home/samba/profiles
;   create mask = 0600
;   directory mask = 0700

[share]
   comment = Ubuntu File Server Share
   path = /storage/share
   read only = no
   guest ok = yes
   browseable = yes
   create mask = 0755

我试过了,但无法显示路径:

<?php 
   $smb = file('smb.conf');
   foreach ($smb as $line) { 
        $trim_line = trim ($line);
        $begin_char = substr($trim_line, 0, 1);
        $end_char = substr($trim_line, -1);
        if (($begin_char == "#") || ($begin_char == ";" || $trim_line == "[global]")) { 
        } 
        elseif (($begin_char == "[") && ($end_char == "]")) { 
            $section_name = substr ($trim_line, 1, -1); echo $section_name . '<br>'; 
        } 
   } //elseif ($trim_line != "") { // $pieces = explode("=", $trim_line , 1); } 
 ?>

【问题讨论】:

  • 你做了什么来尝试解决这个问题?
  • @Roman:我已经编辑了你的帖子;将您的评论复制到帖子中。

标签: php preg-match file-get-contents preg-match-all trim


【解决方案1】:

您可以使用grep/egrep 提取所有这些行:

egrep '^\[].*\]|path\s*=' smb.conf | grep -v '//'  

【讨论】:

  • php中没有egrep
【解决方案2】:

使用这个:

\[share\](?:.|\s)*?path\s*=\s*([^\s]*)

您会发现$matches[1] 应该包含您想要的内容。

工作示例:http://regex101.com/r/kA0oZ9

PHP 代码:

$smbConf = file_get_contents("smb.conf");
preg_match('/\[share\](?:.|\s)*?path\s*=\s*([^\s]*)/im', $smbConf, $matches);
//          ^delimiter                    delimiter^ ^multiline
print_r($matches);

输出:

Array
(
    [0] => [share]
   comment = Ubuntu File Server Share
   path = /storage/share
    [1] => /storage/share
)

【讨论】:

  • 尝试一下,但仍然没有显示
  • 查看代码编辑...您没有使用分隔符或多行/不区分大小写的修饰符。
  • 现在可以工作了,非常感谢。你知道一些解释表达式的页面吗?因为我完全不懂表达。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多