php字符串同义词替换函数


php string synonym replace function

我需要从一个数组或一个文件(最好是一个易于更新的文件)中读取,该文件包含常用单词的缩写词和同义词,并使用它们在字符串中查找和替换。例如,CBN代表"不能否定"。我需要用"不能被否定的国王"代替"CBN国王"。我如何在PHP中做到这一点?

您可以使用INI文件来存储您的翻译表,如下所示(translate.INI):

CBN     = "cannot be negated"
TTYL    = "talk to you later"
.
.
.

将文件读取到数组中,如下所示:

$translate = parse_ini_file( '/path/translate.ini' );

将所有首字母缩略词替换为完整版本:

$toTranslate = "This CBN but it's too late so TTYL";
$translated  = str_ireplace( array_keys( $translate ), array_values( $translate ), $toTranslate );

(请注意使用if str_ireplace()以避免大小写问题)。

如果这不是你经常(或实时)需要做的事情,一个简单的选择就是首先编译"dictionary"文件(比如用制表符分隔的文件,其中包含缩写词和同义词),然后简单地将其中的所有内容读取到哈希表中,然后针对源字符串为哈希表中的每个元素运行str_replace(key,value)。

更新:这里的代码可能看起来像:

$sourceString = 'My very long string full of acronyms like CBN';
$target = '';
//replace the following with file parsing routine
$myDict = array()
$myDict['CBN'] = 'Cannot Be Negated';
...
$myDict['PCBN'] = 'Probably Cannot Be Negated';
$myDict['MDCBN'] = 'Most Definitely Cannot Be Negated';
//replace acronyms with synonyms
foreach($myDict as $synonym=>$acronym)
    $target = str_replace($target, $acronym, $synonym)

更新2:

// reading values from file:
$fp = fopen('dictionary.txt');
while (!eof($fp)) {
     $line = fgets($fp);
     $values = explode("/t", $line);
     //add to dictionary
     $myDict[$values[0]] = $values[1];
}
fclose($fp);