我有一个包含以下内容的文本文件:
---> 12455 ---> 125 ---> KKK
---> 11366 ---> 120 ---> LLL
---> 12477 ---> 120 ---> YYY
我使用以下PHP代码在文件中搜索"--->124",得到以下结果:
---> 12455 ---> 125 ---> KKK
---> 12477 ---> 120 ---> YYY
但我希望结果是这样的:
---> 12455
---> 12477
我希望它只返回第一列。
<?php
$file = 'mytext.txt';
$searchfor = '---> ' . "124";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*'$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)) {
echo implode($matches[0]);
} else {
echo "No matches found";
}
?>
稍微改变一下你的方法。不要将搜索词和分隔符存储在一个字符串中,而是使用两个变量。
$sep = '--->';
$searchfor = '124';
$pattern = "/^$sep's+($searchfor'd+)'s+.*/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo implode(' ', $matches[1])."'n";
}
输出:
12455 12477
演示
首先,分离您的关注点:
- 读取文件
- 分析内容
- 搜索
使用迭代器,您可以在这里实现一些伟大的东西,但它需要对OOP和迭代器接口有更深入的理解。我推荐一种更简单的方法:
<?php
//Read the file line by line
$handle = fopen('file.txt', 'r');
while(!foef($handle)){
$content = fgets($handle);
//Parse the line
$content = explode('---> ', $content);
//Analyse the line
if($content[1] == 124){
echo $content[0]."'n";
}
}
fclose($handle);
应该就是这样,只需按照您所看到的进行调整,我还没有在这里测试代码!
将"/^.*$pattern.*'$/m"
更改为"/$pattern'd*/i"
然后CCD_ 3到CCD_ 4
如果结构始终如您所示,则:
- 逐行读取文件
- 每行CCD_ 5乘以空间CCD_
- 读取结果的元素
[1]
这对我来说似乎是最合乎逻辑的。这里不需要regex
,因为它的工作速度比简单的explode
操作慢。
这里有一个例子:
$handle = fopen( 'file.txt', 'r' );
if ( $handle ) {
while ( ( $line = fgets( $handle ) ) !== false ) {
$matches = explode( ' ', $line );
if ( $matches[4] == '124' )
echo $matches[1] . '<br/>';
}
}
试试这个:
--->'s'd{5}
regex在这里太夸张了,一个简单的explode('--->', $str)
和选择第一个元素就足够了
$file = file_get_contents('file.txt');
$lines = explode('---> ', $file);
for($i=1; $i<count($lines); $i=$i+3)
if(strpos($lines[$i], '124')!==false)
$col[$i/3] = /*'--> ' . */$lines[$i];
print_r($col);
这似乎还不错。如果希望-->包含在输出中,请取消注释上面的注释。此外,生成的$col数组将使用找到的行号进行索引。如果你不想要的话,就用[]替换[$i/3]。
更进一步:
function SearchFileByColumn($contents, $col_num, $search, $col_count = 3) {
$segs = explode('---> ', $contents);
for($i=$col_num; $i<count($segs); $i=$i+$col_count)
if(strpos($segs[$i], $search) !== false)
$res[] = $segs[$i];
return $res;
}
$results = SearchFileByColumn($contents, 1, '124');