我担心速度,因为do循环可能需要运行15-20次。在每个循环中,我搜索并替换几次,并每次从mysql表中选择一次。我只是想让它尽可能快地完成它。
$text = file_get_contents('texts/phir-mohabbat.txt');
preg_match_all('/\S+@/', $text, $words);
preg_match_all('/@\S+/', $text, $lexs);
$count = count($words[0]);
$i = 0;
do {
$bad = array('@', ',', '।', '?');
$word = str_replace('@', '', $words[0][$i]);
$lex = str_replace($bad, '', $lexs[0][$i]);
if($lex == '#') {$lex = $word;}
$get_def = mysqli_query($con,"SELECT * FROM hindi_dictionary WHERE lex = '$lex'");
while($row = mysqli_fetch_array($get_def)) {
$def = $row['def'];
}
$find = array($word.'@'.$lex, $word.'@#');
$replace = '<span class = "word-info" onmouseover="show_info(\''.$lex.' - '.$def.'\',\''.$word.'\');">'.$word.'</span>';
$text = str_replace($find, $replace, $text);
$i++;
} while ($i < $count);
echo nl2br($text);
答案 0 :(得分:1)
我看到@Blorgbeard比我快:) 您可以更改代码以仅调用一次DB - 这应该可以显着提高速度,例如:
...
$res = array();
for($i=0; $i<$count; $i++){
$word = str_replace('@', '', $words[0][$i]);
$lex = str_replace($bad, '', $lexs[0][$i]);
if($lex == '#') {$lex = $word;}
$res[] = $lex;
}
$query = "SELECT * FROM hindi_dictionary WHERE lex in ('";
$query .= implode($res,"','") . "')";
echo $query; // something like: "SELECT * FROM hindi_dictionary WHERE lex in ('a','b','c','f')"
...
并继续像原先预期的那样处理返回的结果集 - 只是现在你将收到所有结果并迭代它们。
<强>注释:强>