【发布时间】:2019-05-26 19:54:17
【问题描述】:
我想用大文件中的代码替换句子。 我曾尝试使用 str_replace,但由于文件中有一些与句子相同的单词,我的代码替换了 them 并且无法识别该句子!
<?php
// sentences,txt
// 12345Temple of Cheope
// ..........
// 99999Cheope
set_time_limit(0);
$GetCodice=@fopen("sentences.txt", "r");
if ($GetCodice) {
while(!feof($GetCodice)) {
$StoreCodice=fgets($GetCodice,4096);
$codice='".'.substr($StoreCodice, 0, 6).'."'; // abcd
$msg=trim(substr($StoreCodice, 6)); // abcd
echo $msg."<br>";
$n=0;
$file = 'longfile.php';
replace_file($file, $msg, $codice);
}
fclose($GetCodice);
}
// From https://stackoverflow.com/questions/2159059/string-replace-in-a-large-file-with-php
function replace_file($path,$string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
echo $replace."<BR>";
return rename($temp, $path);
}
?>
句子是按照它们的降序排列的。我认为这个顺序可以避免用较长的句子替换较短的句子或单词。 我期待输出
12345
.....
99999
但实际输出是
Temple of 9999
.....
99999
我能得到一些帮助吗?
提前谢谢你
【问题讨论】:
-
你好,“一个句子”是什么意思?你的意思是“线”?如果是,请告诉我您是想用您的代码替换一行还是所有行?
-
我的意思是一个句子(“我爱玛丽”、“她不爱我”等),一行可以是很多句子或代码。
-
您的意思是要替换例如:
12345Temple 12345Temple 12345Temple 99999Cheope吗? :12345 12345 12345 99999? -
我想用“9999”替换每次出现的“Cheope”,用“12345”替换“Temple of Cheope”。使用我的代码,我得到“99999”和“99999 神殿”!我必须使用 PHP
标签: php