我使用一个脚本从另一个关键字列表中排除一个单词列表。我想更改输出的格式。(我在这个网站上找到了这个脚本,我做了一些修改。)
示例:
结果短语:我的话
我想添加引号:"我的话"
我想我应该把结果放在new-file.txt中,然后重写它,但我不知道如何获取结果。请给我一些建议。这是我的第一个脚本:)
这是代码:
<?php
$myfile = fopen("newfile1.txt", "w") or die("Unable to open file!");
// Open a file to write the changes - test
$file = file_get_contents("test-action-write-a-doc-small.txt");
// In small.txt there are words that will be excluded from the big list
$searchstrings = file_get_contents("test-action-write-a-doc-full.txt");
// From this list the script is excluding the words that are in small.txt
$breakstrings = explode(',',$searchstrings);
foreach ($breakstrings as $values){
if(!strpos($file, $values)) {
echo $values." = Not found;'n";
}
else {
echo $values." = Found; 'n";
}
}
echo "<h1>Outcome:</h1>";
foreach ($breakstrings as $values){
if(!strpos($file, $values)) {
echo $values."'n";
}
}
fwrite($myfile, $values); // write the result in newfile1.txt - test
// a loop is missing?
fclose($myfile); // close newfile1.txt - test
?>
剧本中也有一个小错误。然而,在test-action-write-a-doc-full.txt
和test-action-write-a-doc-small.txt
中输入单词列表之前,它工作得很好,我必须在第一行加一个换行符,否则它找不到第一个单词。
示例:
test-action-write-a-doc-small.txt
中的单词:
pick,lol,file,cool,
在test-action-write-a-doc-full.txt
中:
pick,bad,computer,lol,break,file。
结果:
Pick=找不到--这是错误。
如果我没有在.txt
中为第一行设置中断,就会发生这种情况
lol=找到
file=找到
提前感谢您的帮助!:)
您可以收集数组中接受的单词,然后将所有这些数组元素粘合到一个文本中,然后将其写入文件。像这样:
echo "<h1>Outcome:</h1>";
// Build an array with accepted words
$keepWords = array();
foreach ($breakstrings as $values){
// remove white space surrounding word
$values = trim($values);
// compare with false, and skip empty strings
if ($values !== "" and false === strpos($file, $values)) {
// Add word to end of array, you can add quotes if you want
$keepWords[] = '"' . $values . '"';
}
}
// Glue all words together with commas
$keepText = implode(",", $keepWords);
// Write that to file
fwrite($myfile, $keepText);
请注意,您不应该像文档中解释的那样编写!strpos(..)
,而应该编写false === strpos(..)
。
还要注意,这种在$file
中搜索的方法可能会给出意外的结果。例如,如果你的$file
字符串中有"悲惨",那么单词"is"(如果在原始文件中用逗号分隔)将被拒绝,因为它在$file中找到。你可能想复习一下。
关于第二个问题
如果不先在文件中添加换行符,它就无法工作,这让我认为它与许多UTF-8
编码文件开头出现的字节顺序标记(BOM)有关。这里和其他地方讨论了这个问题和可能的解决方案。
如果真的是这个问题,我建议有两种解决方案:
使用文本编辑器将文件另存为UTF-8,但不包含BOM表。例如,notepad++
在encoding
菜单中具有这种可能性。
或者,将此添加到您的代码中:
function removeBOM($str = "") {
if (substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
$str = substr($str, 3);
}
return $str;
}
然后用该函数包装所有file_get_contents
调用,如下所示:
$file = removeBOM(file_get_contents("test-action-write-a-doc-small.txt"));
// In small.txt there are words that will be excluded from the big list
$searchstrings = removeBOM(file_get_contents("test-action-write-a-doc-full.txt"));
// From this list the script is excluding the words that are in small.txt
这将从文件中提取的字符串的开头剥离这些有趣的字节。