我想知道是否有人可以帮助解决我似乎无法解决的小问题 - 我的
此刻头在转圈……
好的,我有一个包含大量信息行的 .txt 文件 - 我正在尝试匹配关键字
与这些行并显示一定数量的匹配行。
我将这段脚本放在一起,虽然它有效,但它只匹配一行,如果
单词的顺序与搜索词的顺序相同。
目前举个例子:
搜索词:
red hat
.txt 文件中的行:
这是我的红帽子
我的帽子是红色的
这顶帽子是绿色的
这是一条红领巾
你的红帽子不错
目前的脚本将匹配并显示第 1、5 行
不过我希望它匹配并显示第 1、2、5 行
任何顺序但所有单词都必须存在才能匹配。
我浏览了这里和其他地方的大量帖子,我明白
需要的是分解字符串,然后在循环中搜索每个单词,但是
尽管尝试了几种不同的方法,但我无法让它发挥作用,因为它只是返回
同一条线多次。
在我失去剩下的头发之前,任何帮助将不胜感激:-)
这是我目前正在工作的代码 - 搜索变量已经是
放:
<?php
rawurldecode($search);
$search = preg_replace('/[^a-z0-9\s]|\n|\r/',' ',$search);
$search = strtolower($search);
$search = trim($search);
$lines = file('mytextfile.txt') or die("Can't open file");
shuffle($lines);
$counter = 0;
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false AND $counter <= 4)
{
$found = true;
$line = '<img src=""> <a href="">'.$line.'</a><br>';
echo $line;
$counter = $counter + 1;
}
}
// If the text was not found, show a message
if(!$found)
{
echo $noresultsmessage;
}
?>
预先感谢您的任何帮助 - 仍在学习:-)
这是我的代码:
$searchTerms = explode(' ', $search);
$searchCount = count($searchTerms);
foreach($lines as $line)
{
if ($counter <= 4) {
$matchCount = 0;
foreach ($searchTerms as $searchWord) {
if (strpos($line, $searchWord) !== false ) {
$matchCount +=1;
} else {
//break out of foreach as no need to check the rest of the words if one wasn't found
continue;
}
}
if ($matchCount == $searchCount) {
$found = true;
$line = '<img src=""> <a href="">'.$line.'</a><br>';
echo $line;
$counter = $counter + 1;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)