Replace exact word in PHP array

1

I would like to know how I can replace exactly words in PHP , I currently have this:

$string = "Despues de tomar no maneje, es mejor llamar un taxi";

$exceptions = array(
    "de"  => "DE", 
    "es" => "ES"
);

$conver = str_replace(array_keys($exceptions), $exceptions, $string);

//OUTPUT: DEspuES DE tomar no maneje, ES mejor llamar un taxi

What I want is for it to change only if the word matches and not in all the characters it finds:

Ahem:

  

After DO NOT drive, it is better to call a taxi

    
asked by Raul 08.11.2017 в 18:58
source

2 answers

1

As you comment, the replacement should be done only if the word matches, this is a solution:

$string = "Despues de tomar no maneje, es mejor llamar un taxi";

$exceptions = array(
    "de"  => "DE", 
    "es" => "ES"
);

$strarray = explode(' ', $string);

$newString = "";
for ($var = 0; $var < sizeof($strarray); $var++) {      




   foreach($exceptions as $exception => $exceptionToReplace) {     
      if(strpos($exception, $strarray[$var]) !== False){            
          $newString .= $exceptionToReplace.' ';
          $noChange = false;
          break;
        } else {        
          // NO change                    
          $noChange = true;
        }                 
    }  

    if($noChange)
     $newString .= $strarray[$var].' ';


}

echo $newString;

You will have as a result:

  

After DO NOT drive, it is better to call a taxi

    
answered by 08.11.2017 в 23:20
0

You can use regular expressions

<?php 
$string = "Despues de tomar no maneje, es mejor llamar un taxi";

$exceptions = array(
    "de"  => "DE", 
    "es" => "ES"
);

echo reemplazar($string,$exceptions);

function reemplazar($cadena,$excepciones)
{
    $stringRet = $cadena;
    foreach ($excepciones as $key => $value) {
        $stringRet = preg_replace("/\b$key\b/", $value, $stringRet);
    }
    return $stringRet;
}

Entry:

  

After you have not driven, it is better to call a taxi

Exit:

  

After DO NOT drive, it is better to call a taxi

    
answered by 09.11.2017 в 02:12