Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 941
Dani Avatar asked Aug 11 '11 13:08

Dani


2 Answers

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');
like image 118
Emil Vikström Avatar answered Sep 28 '22 09:09

Emil Vikström


You might want to try this

<?php
$string = 'black';
$pattern = '/([aeiou])/i';
$replacement = '[aeiou]';
echo preg_replace($pattern, $replacement, $string);
?>
like image 33
az4dan Avatar answered Sep 28 '22 08:09

az4dan