Php 如何使用file\u get\u contents和preg\u match从文件中获取特定数据
我想从smb.conf获取关于共享文件夹[share]和path“path=”的数据,但我想跳过其中的行;及// 谢谢你的回答 示例smb.confPhp 如何使用file\u get\u contents和preg\u match从文件中获取特定数据,php,preg-match,file-get-contents,preg-match-all,trim,Php,Preg Match,File Get Contents,Preg Match All,Trim,我想从smb.conf获取关于共享文件夹[share]和path“path=”的数据,但我想跳过其中的行;及// 谢谢你的回答 示例smb.conf ;[profiles] ; comment = Users profiles ; path = /home/samba/profiles ; create mask = 0600 ; directory mask = 0700 [share] comment = Ubuntu File Server Share pat
;[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); }
?>
使用以下方法:
\[share\](?:.|\s)*?path\s*=\s*([^\s]*)
您会发现,$matches[1]
应该包含您想要的内容
工作示例:
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
)
您可以使用
grep
/egrep
提取所有这些行:
egrep '^\[].*\]|path\s*=' smb.conf | grep -v '//'
你做了什么来试图解决这个问题?@Roman:我编辑了你的帖子;已将您的评论复制到帖子中。phpa中没有egrep请尝试此操作,但仍然没有显示See code edit。。。您没有使用分隔符或多行/不区分大小写的修饰符。现在可以使用了,非常感谢。你知道哪一页是解释表达式的吗?因为我完全不懂表达。谢谢