回到 2002 年 10 月,csnyder at chxo dot com 寫了關於拼寫函式的第一條評論,並透過直接呼叫 aspell 編寫了一個非常複雜的拼寫檢查。同樣地,我編寫了一個簡化的 PHP 函式,它可以拼寫檢查字串,並在拼錯的單字前後插入標籤。不提供自動更正功能。
<?
function spellcheck($string) {
// 輸入:$string:要拼寫檢查的文字。
// 返回:在拼寫錯誤之前和之後插入「<strong>」和「</strong>」的字串。
//
$pre='<strong>'; // 在每個拼寫錯誤之前插入。
$post='</strong>'; // 在每個拼寫錯誤之後插入。
$string=strtr($string,"\n"," ");
// 刪除字串中的換行符。(在這種情況下,它會干擾 aspell。)
$mistakes = `echo $string | /usr/local/bin/aspell list`;
// 取得錯誤列表。
$offset = 0;
foreach (explode("\n", $mistakes) as $word)
// 遍歷列表,插入 $pre 和 $post 字串。我沿著列表移動並
// 進行插入,並持續追蹤位置。使用 str_replace($string, $pre.$work.$post) 進行全局替換
// 如果同一個拼寫錯誤出現多次,就會產生問題。
if ($word != "") {
$offset = strpos($string, $word, $offset);
$string = substr_replace($string, $post, $offset + strlen($word), 0);
$string = substr_replace($string, $pre, $offset, 0);
$offset = $offset + strlen($word) + strlen("$pre $post");
};
return $string;
?>
要在您的系統上運行此程式,請檢查 /usr/local/bin/aspell list 是否可以從 shell 執行。它需要從標準輸入獲取輸入。由於在 PHP 呼叫中,PATH 變數可能與 shell 呼叫中的不同,因此您可能無法在沒有路徑的情況下為 PHP 執行 aspell。