2014-01-07 38 views
-1

我想从smb.conf获取关于共享文件夹[share]和路径“path =”的数据,但我想跳过一行;和// 感谢您的回答。如何使用file_get_contents和preg_match从文件中获取特定数据

样品的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); } 
?> 
+0

你已经做了什么来尝试解决这个问题? – Rottingham

+0

@Roman:我编辑了你的帖子;将您的评论复制到帖子中。 –

回答

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 
) 
+0

我不知道为什么,但没有显示任何内容。 – Roman

+0

@Roman doh!你是对的。修复一秒钟。 – brandonscript

+0

@Roman固定,请参阅编辑。 – brandonscript

0

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

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

在php中没有egrep – 2014-01-07 19:24:24

相关问题