如何使用file_get_contents和preg_match从文件中获取特定数据

时间:2014-01-07 19:14:54

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

我想从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); } 
 ?>

2 个答案:

答案 0 :(得分:0)

使用此:

\[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
)

答案 1 :(得分:0)

您可以使用grep / egrep

提取所有这些行
egrep '^\[].*\]|path\s*=' smb.conf | grep -v '//'