Php str_replace replace itself

I need to replace each occurrence of one of the letters a, o, i, e, uon [aoieu]?
I tried to do the following:

str_replace(array('a', 'o', 'i', 'e', 'u'), '[aoieu]?', $input);

But when he enters a value blackinstead of giving me the expected bl[aoieu]?ck, he gave me

bl[a[ao[aoi[aoie[aoieu]?]?[aoieu]?]?[aoie[aoieu]?]?[aoieu]?]?[aoi[aoie[aoieu]?]?[aoieu]?]?[aoie[aoieu]?]?[aoieu]?]?ck

How can I get him not to replace things that he has already replaced?

+5
source share
7 answers

You can use a regular expression for this, or you can make your own function that performs a sequence one letter at a time. The regex is used here:

preg_replace('/[aoieu]/', '[aoieu]?', $input);

( , $search char , - strpos , , ):

function safe_replace($search, $replace, $subject) {
  if(!is_array($search)) {
    $search = array($search);
  }
  $result = '';
  $len = strlen($subject);
  for($i = 0; $i < $len; $i++) {
    $c = $subject[$i];
    if(in_array($c, $search)) {
      $c = $replace;
    }
    $result .= $c;
  }
  return $result;
}
//Used like this:
safe_replace(array('a', 'o', 'i', 'e', 'u'), '[aoieu]?', 'black');
+4

:

gotcha

str_replace() , .

+3

,

<?php
$string = 'black';
$pattern = '/([aeiou])/i';
$replacement = '[aeiou]';
echo preg_replace($pattern, $replacement, $string);
?>
+2

strtr:

$result = strtr($input, array('a' => '[aoieu]?', 
                         'o' => '[aoieu]?', 
                         'i' => '[aoieu]?', 
                         'e' => '[aoieu]?', 
                         'u' => '[aoieu]?'));
+2
$input = str_replace(array('a', 'o', 'i', 'e', 'u'),   '~',          $input);
$input = str_replace('~',                              '[aoieu]?',   $input);
0

:

$output = preg_replace('/[aeiou]/', '[aeiou]?', $input);
0

, preg_replace, (. Thax, Emil ..). , , , tokenize:

$token = '{{{}}}';
// replace the temporary value with the final value
str_replace( $token, '[aoieu]?', 
    // replace all occurances of the string with a temporary value.
    str_replace( (array('a', 'o', 'i', 'e', 'u'), $token, $input ) );
0

All Articles