我试图找出使用多个排序规则进行字符串替换的最佳方法.
我有一个由用户插入的句子,我有一个数组,其中包含该句中所有拼写错误的单词及其可能的更正.
$sentence =’我想从出租车里恢复我的车辆’;
>我想从出租车上恢复我的车辆
>我想从出租车里恢复我的车辆
>我想从出租车上取回我的车辆
代码到目前为止:
$element = array( "vehical" => array('vehicle'),"recovary" => array('recovery','recover','revary') ); $sentence = 'i want to recovary my vehical from the cabs'; foreach($element as $i => $val){ echo $i; }
编辑:扩展了另一种情况:
如果顶部数组中存在多个变体,会发生什么.
"vehical" => array('vehicle','vehiclesy','whatever'),'revary')
>我想从出租车上恢复我的车辆
>我想从出租车里恢复我的车辆
>我想从出租车中恢复我的任何东西
>我想从出租车里恢复我的车辆
>我想从出租车里恢复我的车辆
>我想从出租车里找回我的东西
>我想从出租车上取回我的车辆
>我想从出租车里复活我的车辆
>我想要从出租车里复活我的任何东西
您需要创建替换数据的所有唯一组合.对于这些组合中的每一种,您都可以进行替换.这是一种方法:
原文链接:https://www.f2er.com/php/134227.html<?PHP function createCombinations(array $input) { $head = array_shift($input); $tail = count($input) > 1 ? createCombinations($input) : array_shift($input); $combinations = []; foreach ($head as $left) { foreach ($tail as $right) { $combinations[] = array_merge([$left],(array) $right); } } return $combinations; } $element = [ 'vehical' => ['vehicle','car'],'recovary' => ['recovery','revary'],'cubs' => ['cabs'],]; $sentence = 'i want to recovary my vehical from the cubs'; $from = array_keys($element); foreach (createCombinations($element) as $to) { echo str_replace($from,$to,$sentence),"\n"; } # => i want to recovery my vehicle from the cabs # => i want to recover my vehicle from the cabs # => i want to revary my vehicle from the cabs # => i want to recovery my car from the cabs # => i want to recover my car from the cabs # => i want to revary my car from the cabs