Skip to content
Advertisement

php str_replace replacing itself

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

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

But when giving it input of black instead of giving me the expected bl[aoieu]?ck it gave me

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

How can I get it to not replace things it already replaced?

Advertisement

Answer

You can consider using a regular expression for this, or you can make your own function which steps through the string one letter at a time. Here’s a regex solution:

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

Or your own function (note that $search only can be a single char or an array of chars, not strings – you can use strpos or similar to build one which handles longer strings as well):

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');
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement