【问题标题】:PHP to search/filter text filePHP搜索/过滤文本文件
【发布时间】:2015-02-05 17:51:30
【问题描述】:

如标题所述,如何使用 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;
?>

【问题讨论】:

  • 为什么投反对票?改为提问
  • 参考这个网址google.co.in/…
  • 我更新了我的示例代码。为了更准确地回答我的问题,我想我想要做的是过滤匹配的行以仅将某个字段存储为 $lat @manuyd
  • 你是说线路?不清楚你想说什么
  • 是的,grep 将返回匹配的整行,然后我想将其过滤到我想要的字段

标签: php html shell


【解决方案1】:

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

$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";

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2020-06-07
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多