2012-01-27 34 views
2

我有一个变量,像这样的值:PHP的preg_match找到相关词语

$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'); 

我想找个只是“知道的',然后替换为'专注于'。输出象下面这样:

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

只有

搜索“知道”作为相关同义词替换而不是别人。谢谢你的帮助。

好吧,这里的新代码:

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

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

这是一个动态数组($searches),希望大家理解......我们知道,以获得最佳代名词更换使用“”注意'取代'专心'。输出象下面这样:

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

+0

排序字符串长度的搜索模式。并且可能在它们周围使用'\ b'锚。 – mario 2012-01-27 09:27:11

+0

请在PHP中显示代码? – 2012-01-27 09:41:04

回答

0

如何:

$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; 

输出:

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

感谢M42。完美的解决方案! :) – 2012-01-28 00:21:05

+0

@XioJin:不客气。 – Toto 2012-01-28 10:50:27

1

我假设你的搜索&顶替阵列是静态的。

试试这个,

str_replace($searches[3],$replaces[3],$sentence)

而且只需更换特定的 “提防” 你可以简单地做:

str_replace("%be aware of%","concentrate on",$sentence)

+0

请注意,我只需要从具有相同单词的$搜索中替换相关同义词。从最大匹配的地方来看,这并不成问题。 – 2012-01-27 09:34:00

+0

不,这不是静态数组..这是一个随机排列... – 2012-01-27 09:35:55

+0

雅,所以在这种情况下,简单地使用'str_replace函数($搜索,$取代,$主题);' – Rikesh 2012-01-27 09:36:05

1

无需这里正则表达式,

首先以某种方式对您的常量数组进行排序,找到最大的匹配:

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

然后使用str_replace函数

$newsentence=str_replace($searches,$replaces, $sentence); 
+0

请注意,我只需要从具有相同单词的$搜索中替换相关的同义词。从最大匹配的地方来看,这并不成问题。 – 2012-01-27 09:33:38

+0

@XioJin这就是为什么我重新排列'$ replaces'以同样的方式,我重新排序'$ searches' – 2012-01-27 09:36:13

+0

$搜索的动态数组,你不能下令值。只要搜索匹配同义词替换,我们知道真正的同义词是“知道” – 2012-01-27 09:37:49

1

如果您改变了搜索的顺序,使第一个元素不能元素后数组中的匹配,你可以使用str_replace($searches, $replaces, $subject);正常!

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

如果字符串包含“be aware”,“be aware of”将不匹配并且“be aware”将会。如果你有相反的顺序,“知道”会匹配“be aware”,这将是错误的。

+0

请注意,我只需要更换从$搜索相关的同义词有相同的词。从最大匹配的地方来看,这并不成问题。 – 2012-01-27 09:33:19

+0

@XioJin你从哪里获得搜索并从中取代?如果它来自SQL,则可以使用SQL进行排序,这会更容易... – 2012-01-27 10:48:01