我试图找出使用多个排序规则进行字符串替换的最佳方法.
我有一个由用户插入的句子,我有一个数组,其中包含该句中所有拼写错误的单词及其可能的更正.
$sentence = 'i want to recovary my vehical from the cabs';
我想显示以下内容:
代码到目前为止:
$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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:扩展了另一种情况:
如果顶部数组中存在多个变体,会发生什么.
"vehical" => array('vehicle', 'vehiclesy', 'whatever'),
"recovary" => array('recovery', 'recover', 'revary')
Run Code Online (Sandbox Code Playgroud)
您需要创建替换数据的所有唯一组合。对于每个组合,您都可以进行替换。这是一种方法:
<?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', 'recover', '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
Run Code Online (Sandbox Code Playgroud)
演示: https: //ideone.com/LERb9X
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |