且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP preg_match找到相关的字

更新时间:2022-10-14 21:46:43

如何

  $一句话=当谈到时间更新您的汽车保险政策,了解您的运营商如何处理续费;
$搜索=阵列('知道','知道','知道','知道');
$代替=阵列('意识','自觉','记','专心');功能CMP($ A,$ B){
    如果(strpos($ A,$ B)==假的!),返回-1;
    如果(strpos($ B $ A)==假的!),返回1;
    返回0;
}uasort($搜索,'CMP');
$ replaces_new =阵列();
$ I = 0;
的foreach($搜索为$ K => $ V){
    $ replaces_new [$ i] = $替换[$ k]的;
    $ I ++;
}$解析度= str_replace函数($搜索,$ replaces_new,$句);
回声$水库;

输出:

 当谈到时间更新您的汽车保险政策,专注于运营商如何处理续费

I have a variable with value like this :

$sentence = "When it comes time to renew your auto insurance policy, be aware of how your carrier handles renewals";

And I have array variables with value below :

$searches = array('aware', 'aware of', 'be aware', 'be aware of');

$replaces = array('conscious', 'conscious of', 'remember', 'concentrate on');

I would like to find just 'be aware of' and then replace with 'concentrate on'. Output like below :

When it comes time to renew your auto insurance policy, concentrate on how your carrier handles renewals

Search only 'be aware of' as relevant synonym replacement not others. Thanks for your help.

Ok, here the new code:

$searches = array('aware of', 'be aware of', 'be aware', 'aware');

$replaces = array('conscious of', 'concentrate on', 'remember', 'conscious');

This is a dynamic array ($searches), I hope you understand...and we know to get the best synonym replacement is use ''be aware of' to replace with 'concentrate on'. Output like below :

When it comes time to renew your auto insurance policy, concentrate on how your carrier handles renewals

How about:

$sentence = "When it comes time to renew your auto insurance policy, be aware of how your carrier handles renewals";
$searches = array('aware', 'aware of', 'be aware', 'be aware of');
$replaces = array('conscious', 'conscious of', 'remember', 'concentrate on');

function cmp($a, $b) {
    if (strpos($a, $b) !== false) return -1;
    if (strpos($b, $a) !== false) return 1;
    return 0;
}

uasort($searches, 'cmp');
$replaces_new = array();
$i=0;
foreach($searches as $k=>$v) {
    $replaces_new[$i] = $replaces[$k];
    $i++;
}

$res = str_replace($searches, $replaces_new, $sentence);
echo $res;

output:

When it comes time to renew your auto insurance policy, concentrate on how your carrier handles renewals