php - Foreach string replacement with multiple variations -
i trying find out best way of going string replacement multiple collations.
i have sentence inserted user, have array of miss-spelled words in sentence , potential corrections.
$sentence = 'i want recovary vehical cabs';
i want display following:
- i want recovery vehicle cabs
- i want recover vehicle cabs
- i want revary vehicle cabs
code far:
$element = array( "vehical" => array('vehicle'), "recovary" => array('recovery', 'recover', 'revary') ); $sentence = 'i want recovary vehical cabs'; foreach($element $i => $val){ echo $i; }
edit: expanded scenario:
what happen if there more 1 variation in top array.
"vehical" => array('vehicle', 'vehiclesy', 'whatever'), "recovary" => array('recovery', 'recover', 'revary')
- i want recovery vehicle cabs
- i want recovery vehiclesy cabs
- i want recovery whatever cabs
- i want recover vehicle cabs
- i want recover vehiclesy cabs
- i want recover whatever cabs
- i want revary vehicle cabs
- i want revary vehiclesy cabs
- i want revary whatever cabs
you need create unique combinations of replacement data. each of combinations can replacement. 1 way it:
<?php function createcombinations(array $input) { $head = array_shift($input); $tail = count($input) > 1 ? createcombinations($input) : array_shift($input); $combinations = []; foreach ($head $left) { foreach ($tail $right) { $combinations[] = array_merge([$left], (array) $right); } } return $combinations; } $element = [ 'vehical' => ['vehicle', 'car'], 'recovary' => ['recovery', 'recover', 'revary'], 'cubs' => ['cabs'], ]; $sentence = 'i want recovary vehical cubs'; $from = array_keys($element); foreach (createcombinations($element) $to) { echo str_replace($from, $to, $sentence), "\n"; } # => want recovery vehicle cabs # => want recover vehicle cabs # => want revary vehicle cabs # => want recovery car cabs # => want recover car cabs # => want revary car cabs
Comments
Post a Comment