空格的正则表达式,但不是转义空格
我正在解析 ls -lb 的输入并尝试将每个字段放入 PHP 中的数组中。
我的输入看起来像这样:
-rwx------ 1 user.name users 546879 2008-09-05 09:23 Newspaper_Templates.pdf
-rwx------ 1 user.name users 403968 2009-01-12 14:16 P2_05.ppt
-rwx------ 1 user.name users 144896 2009-01-12 14:08 P2.5_Using_CRO.ppt
drwx------ 8 user.name users 4096 2009-09-15 10:21 School\ 09-10
drwx------ 2 user.name users 4096 2010-06-28 13:59 SMART\ Notebook
drwx------ 2 user.name users 4096 2009-11-30 13:35 Templates
我一次查看每一行,并尝试用一个空格替换多个空格,除了用 . 转义的空格之外。
每一行都被读入一个名为 $filedata 的变量,然后执行以下操作:
$filedata = preg_replace("/\s+/", " ", $filedata);
print_r (preg_split("/[\s]/", $filedata));
这几乎可以工作,但对于带有转义空格的行,显然不行。我如何修改它,以便我的分割适用于空格,但不适用于转义空格?
(或者,还有更好的方法吗?如果我能让 ls 给我列出每个字段用逗号或其他东西分隔的列表,那就更好了!)
I am parsing the input of ls -lb and trying to put each field into an array in PHP.
My input looks something like this:
-rwx------ 1 user.name users 546879 2008-09-05 09:23 Newspaper_Templates.pdf
-rwx------ 1 user.name users 403968 2009-01-12 14:16 P2_05.ppt
-rwx------ 1 user.name users 144896 2009-01-12 14:08 P2.5_Using_CRO.ppt
drwx------ 8 user.name users 4096 2009-09-15 10:21 School\ 09-10
drwx------ 2 user.name users 4096 2010-06-28 13:59 SMART\ Notebook
drwx------ 2 user.name users 4096 2009-11-30 13:35 Templates
I'm looking at each line at a time, and trying to replace multiple spaces with a single space, apart from ones that are escaped with a .
Each row is read into a variable called $filedata, then put through this:
$filedata = preg_replace("/\s+/", " ", $filedata);
print_r (preg_split("/[\s]/", $filedata));
This almost works, but for the rows with the escaped spaces, it obviously doesn't. How can I modify this so that my split works for spaces, but not escaped spaces?
(Alternatively, is there a better way? If I could get ls to give me the listing with each field seperated by a comma or something, that would be even better!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,鉴于您正在使用
preg
函数,您可以使用 否定后向断言:(? 被 PHP 字符串处理为
(? 表示测试空白之前的字符不是
\
Yes, given that you are using the
preg
functions, you can use the negative look-behind assertion:The
(?<!\\\\)
gets processed by the PHP string to be(?<!\\)
which means test that the character before the white space is not a\
这是一种非常容易出错的获取文件信息的方法。
为此,请使用 PHP 函数
stat
。That is a very error prone way to get file info.
Use the PHP function
stat
for this purpose.尝试使用
(?
Try with
(?<!\\)\s+