开发者

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[aoi开发者_如何学Ce[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?


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');


You might want to try this

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


Taken from the documentation:

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.


I recommend avoiding preglike functions and using strtr().

This native function

  • makes a single pass over the input string,
  • does not replace replacements, and
  • finds the longest matching substring to replace (when a qualifying string is found within another qualifying string)

Code:

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


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


Here it is:

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


You might be able to get preg_replace to handle this for you (see Thax, Emil, etc.'s answers). Otherwise, if that is too complicated, you can, 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜