php字符串同义词替换功能

时间:2012-04-01 05:45:41

标签: php replace

我需要从数组或文件中读取(最好是文件以便更新),其中包含常用词的首字母缩写词和同义词,并使用它来查找和替换字符串。例如,说CBN代表“不能被否定”。我需要用“不能否定之王”取代“CBN之王”。我怎么能用PHP做到这一点?

2 个答案:

答案 0 :(得分:1)

如果不是你需要经常(或实时)做的事情,一个简单的选择就是首先编译“字典”文件(让我们说制表符分隔,包含首字母缩略词和同义词),然后简单地阅读全部将其内容放入哈希表中,然后针对源字符串为哈希表中的每个元素运行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);

答案 1 :(得分:1)

您可以使用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 );

(请注意使用str_ i 替换()以避免出现问题)。