PHP搜索/过滤文本文件

时间:2014-12-08 05:16:51

标签: php html shell

正如标题所述,我如何使用PHP和变量搜索文本文件。我想将用户文本存储到变量中,并将其用作newplaces.txt文件中的搜索参数。我知道以下代码不起作用,但希望能够实现我想要完成的任务。我可以在文件中找到匹配项,但我需要帮助将该行过滤到我需要的字段

<form method="post" action"http...">
Enter City and State <input name='place' type="text" size="10">
<input type="submit" value="Submit">
</form>
<?php
$f="/newplaces.txt";
$o=file($f);

$a=$_POST['place'];

$c=preg_grep("/\b$a\b/", $o);
echo implode($c, ' ');

$lat=exec("grep -i $a $f | cut -d' '' -f10 ");  //Need help with filtering the match
echo $lat;
?>

1 个答案:

答案 0 :(得分:0)

从您的shell代码"grep -i $a $f | cut -d' '' -f10 "判断,您只需要匹配行中第10个以空格分隔的字段。这可以通过explode轻松完成,例如。克。

$fields = explode(' ', $c[1]);  # $c[1] is the first matching line from the preg_grep()
$lat = $fields[10];             # $fields[10] now is the 10th field from that line
echo "The 10th field is '$lat'.\n";