gpt4 book ai didi

php - 具有多种变体的 Foreach 字符串替换

转载 作者:可可西里 更新时间:2023-11-01 12:36:04 25 4
gpt4 key购买 nike

我正在尝试找出使用多个排序规则替换字符串的最佳方法。

我有一个由用户插入的句子,我有一个数组,其中包含该句子中所有拼写错误的单词及其可能的更正。

$sentence = '我想从出租车上取回我的车辆';

我想显示以下内容:

  1. 我想从出租车里取回我的车
  2. 我想从出租车里取回我的车
  3. 我想从出租车上换车

到目前为止的代码:

$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'),
"recovary" => array('recovery', 'recover', 'revary')
  1. 我想从出租车里取回我的车
  2. 我想从出租车上恢复我的车辆
  3. 我想从出租车上拿回我的东西
  4. 我想从出租车里取回我的车
  5. 我想从出租车上恢复我的车辆
  6. 我想从出租车上拿回我的东西
  7. 我想从出租车上换车
  8. 我想从出租车上换车
  9. 我想从出租车上取回我的任何东西

最佳答案

您需要创建所有唯一的替换数据组合。对于这些组合中的每一个,您都可以进行替换。这是一种方法:

<?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

演示:https://ideone.com/LERb9X

关于php - 具有多种变体的 Foreach 字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38458088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com