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:

  1. i want recovery vehicle cabs
  2. i want recover vehicle cabs
  3. 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') 
  1. i want recovery vehicle cabs
  2. i want recovery vehiclesy cabs
  3. i want recovery whatever cabs
  4. i want recover vehicle cabs
  5. i want recover vehiclesy cabs
  6. i want recover whatever cabs
  7. i want revary vehicle cabs
  8. i want revary vehiclesy cabs
  9. 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 

demo: https://ideone.com/lerb9x


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -