简体   繁体   中英

PHP str_replace Replacing Two words

My code is below..

echo $type = str_replace(array('q','h','f'),array('Quarter','Half','Full'),$_POST['type']);

here on the above line $_POST['type'] have These 3 values;

  1. $_POST type = 'q'
  2. $_POST type = 'h'
  3. $_POST type = 'f'

I want to replace

  • q with Quarter
  • h with Half
  • f with Full.

My Problem is when $_POST['type']='h',

The result of above code means value of $type came HalFull .

Why this is happening...

Is there any solution for this...?

Thanks

The problem

str_replace is executed consecutively for each of the three parameters.

For the first parameter, nothing is replaced.

For the second parameter, h is replaced by Half .

For the second parameter, the f of Half is replaced by Full .

So you end up with HalFull .


The solution

There's many approaches to tackle this issue.

The simplest solution would be to use preg_replace instead, and refine your search criteria :

echo $type = preg_replace(array('/^q/i','/^h/i','/^f/i'),array('Quarter','Half','Full'),'h');

It seems like it is replacing h with Half and then the last f of Half with Full

May be if you can provide a regexp that only replaces if the source string is exactly one character, then it would work.

Try this:

echo $type = preg_replace(array('/^q$/i','/^h$/i','/^f$/i'),array('Quarter','Half','Full'),$_POST['type']);

It works

If you change the order of replacements, you'll be fine:

echo $type = str_replace(array('q','f','h'),array('Quarter','Full','Half'),$_POST['type']);

..because 'f' produces 'Full', and 'Full' doesn't have any 'h's in, so the next replacement is safe.

Or you could perhaps choose a completely different approach, which would be safer, and I dare say a little more readable and maintainable.

$translate = array(
  'q' => 'Quarter',
  'h' => 'Half',
  'f' => 'Full'
);

echo $type = $translate[$_POST['type']];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM