这是我的代码
$words=$_GET['word'];
$words=explode(' ',$words);
$words=implode('|',$words);
$search=shell_exec( 'grep -E '.$words.'
/home/jitu/data.txt');
$search=explode('n',$search);
foreach($search as $line){echo '<p>'.$line.'</p>';}
此代码最适用于单个搜索词,但不适用于多个词
在shell_exec中使用$words变量时,需要将其括在引号内
"|"(管道符号(将左侧命令的结果传递给右侧命令。
您的shell正在执行以下操作:
$: grep -E one|two|three data.txt
bash: two: command not found
bash: three: command not found
应该在什么时候执行:
$: grep -E 'one|two|three' data.txt
one
two
代码:
<?php
$words="one two three";
$words=explode(' ',$words);
$words=implode('|',$words);
$search=shell_exec( "grep -E '{$words}' data.txt");
$search=explode('n',$search);
foreach($search as $line){echo '<p>'.$line.'</p>';};
顺便说一句,当您将用户提供的输入传递给shell_exec而不首先对其进行清理时,您将很容易受到代码执行的影响。
使用shell不是一个好方法。PHP已经有了可以做到这一点的函数。我会使用preg_match_all
和file_get_contents
。这假设文件不是很大,如果是的话,可能需要fread
。
$words = $_GET['word'];
$words = explode(' ',$words);
$words = implode('|',$words);
$file = file_get_contents('/home/jitu/data.txt');
preg_match_all('/^.*b(' . $words . ').*$b/m', $file, $search);
foreach($search[0] as $line){
echo '<p>'.$line.'</p>';
}
我还在正则表达式中添加了单词边界,这样部分单词就不会匹配。m
修饰符使^$
每行匹配,而不是整个文件。.*
是这样,比赛前后的一切都会被捕捉到。如果你只是想知道哪些术语是匹配的,可以使用$search[1]
。
另外需要注意的是,用户输入永远不应该直接传递到shell。