php preg_match_all 截取 xml 内容,PHP preg_match_all,读取内容并排除不需要的内容

我想要读取一个文本文件,但排除在开始时包含某些字符的行(因此“@”或稍后定义的任何一行):

@ I don't want this line to be read

This line should be read;

"This one" should be read, too;

'Also this one' should be read;

...etc

@ But this one should be ignored;用下面的代码我可以分解以分号(“;”)结尾的代码,但最后一行不应该,因为它以“@”开头。

$contents = file_get_contents($the_path);

$result = array_map('trim', explode(";", $contents));任何暗示要达到这个目标?谢谢

更新代码:

// http://stackoverflow.com/questions/10257244/php-preg-match-all-read-content-and-exclude-unwanted/10257319

$results = array();

$matches = array();

$the_path = '/path/to/file.txt';

if (is_file($the_path)) {

$contents = file_get_contents($the_path);

if ($contents) {

// ! array warning

// $contents = array_map('rtrim', $contents);

// $matches = preg_grep('#^@#', $contents, PREG_GREP_INVERT);

$matches = preg_split("/[\r\n]/", preg_replace("/@.*?[\r\n]/", "", $contents), NULL, PREG_SPLIT_NO_EMPTY);

if ($matches) {

foreach ($matches as $key => $val) {

$results[$key] = $val;

}

}

}

}

// Attempt to remove the first 0 key, and start from 1, because 0|value0 is considered NULL

$results = array_combine(range(1, count($results)), array_values($results));

return !empty($results) ? $results : array();更新2,通过DCoder正常工作:

$matches = array();

if ($contents = file($the_path)) {

$contents = array_map('rtrim', $contents);

$keyword = '@';

// Still output @line

// $matches = preg_grep('#^@#', $contents, PREG_GREP_INVERT);

// Ok, thanks to http://php.net/manual/de/function.preg-grep.php#85503

$matches = preg_grep("/{$keyword}/i", $contents, PREG_GREP_INVERT);

// $matches = preg_split("/[\r\n]/", preg_replace("/@.*?[\r\n]/", "", $contents), NULL, PREG_SPLIT_NO_EMPTY);

// dsm($matches);

if ($matches) {

foreach ($matches as $key => $match) {

$results[$key] = $match;

}

}

}

// $results = array_combine(range(1, count($results)), array_values($results));

return $results;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值