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

Posted

技术标签:

【中文标题】具有多种变体的 Foreach 字符串替换【英文标题】:Foreach string replacement with multiple variations 【发布时间】:2016-11-22 07:44:17 【问题描述】:

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

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

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

编辑:扩展另一个场景:

如果顶部数组中有多个变化会发生什么。

    "vehical" => array('vehicle', 'vehiclesy', 'whatever'),
    "recovary" => array('recovery', 'recover', 'revary')
    我想从出租车里找回我的车 我想从出租车里找回我的车辆 我想从出租车里拿回我的任何东西 我想从出租车里找回我的车 我想从出租车里找回我的车辆 我想从出租车里拿回我的任何东西 我想从出租车上改装我的车 我想把我的车辆从出租车上调下来 我想从出租车上拿回我的任何东西

【问题讨论】:

【参考方案1】:

尽量用str_replace()点赞,

$str='';
foreach($element as $search => $combinations)
     foreach($combinations as $comb)
        $str.=str_replace($search,$comb,$sentence)."\n";
     

echo $str;

Demo

尝试创建函数并创建一个包含所有可能组合的数组,然后使用生成的数组替换它,例如,

$element = array(
    "vehical" => array('vehicle', 'vehiclesy', 'whatever'),
    "recovary" => array('recovery', 'recover', 'revary')
);

$sentence = 'i want to recovary my vehical from the cabs';

// change the array using loop for replacement
function makeCombinations($combinations, $values)

    $res = array();
    $i=0;
    foreach($combinations as $comb) 
        foreach($values as $value) 
            $res[$i] = is_array($comb) ? $comb : array($comb);
            $res[$i][] = $value;
            $i++;
        
    
    return $res;
   

$searchArr = array();
foreach($element as $search => $values) 
    $searchArr[] = $search;
    $combinations = isset($combinations) ? makeCombinations($combinations, $values) : $values;


// finally replace the strings
foreach($combinations as $combination)
    echo str_replace($searchArr, $combination, $sentence),"\n";

Demo

【讨论】:

刚刚扩展了问题 - 道歉:( @SophieRhodes 试试我的回答,它按您的预期工作。【参考方案2】:

尝试以下解决方案,使用几秒钟(foreach 和 str_replace()):

//the items with replacement values.
$items = array(
    "vehical" => array('vehicle', 'vehiclesy', 'whatever'),
    "recovary" => array('recovery', 'recover', 'revary'),
    "cabs" => array('cups', 'cips'), 
    "from" => array(1, 2)
);

//init the initial sentence and the array with all solutions.
$sentence = 'i want to recovary my vehical from the cabs';
$solution = [];

//run through all keywords to execute the replacements.
foreach ($items as $item => $value) 
    if (count($value) > 0) 
        if (count($solution) > 0) 
            $solution = getReplacements($solution, $item, $value);
         else 
            $solution = getReplacements($sentence, $item, $value);
        
    


//output the solutions.
array_walk_recursive($solution, 'output');

function output(&$item,$key) 
    echo $item."\n";


/**
 * Function to execute the replacements.
 * @param array|string $sentence An array or string on which the replacements should execute.
 * @param string $item The word which will be replaced.
 * @param array $values The replacement values for the item.
 * @return array An array with all solutions of this function.
 */
function getReplacements($sentence, $item, $values)

    $solutions = [];

    foreach ($values as $value) 
        $sol = str_replace($item, $value, $sentence);

        if (is_array($sol)) 
            $solutions = array_merge($solutions, $sol);
         else 
            $solutions[] = $sol;
        
    

    return $solutions;

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

【讨论】:

刚刚扩展了问题 - 道歉:( 更新了我的答案... - 现在使用两个数组并且没有错误的句子。【参考方案3】:

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

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

【讨论】:

以上是关于具有多种变体的 Foreach 字符串替换的主要内容,如果未能解决你的问题,请参考以下文章

如何在PowerShell中使用运算符'-replace'来替换具有特殊字符的文本字符串并成功替换

Kotlin字符串操作 ② ( 字符串替换函数 replace | 字符串比较操作符 == 和 === | 字符串遍历 forEach )

搜索和替换

具有确定(少量)变体的哈希/摘要

如何获取具有特定名称/值的所有变体ID

查找和替换字符串