Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace exact string in another string

I have array of vars

array(2) {  
  ["M"]=>
  string(3) "500"
  ["MA"]=>
  string(3) "200"
}

AND strings "1000-M", "1000-MA", "1000+MA-M", "MA/2", "M*MA+100"

And I need to replace M with value 500, and MA with value 200. When I use str_replace it works but only for M, because it still match with first var M

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks for help

>Solution :

You can sort your replace array by longest keyword first, so that it will be replaced first, and only later on replace shorter keys:

$strings = ["1000-M", "1000-MA", "1000+MA-M", "MA/2", "M*MA+100"];

$replace = ['M' => '500', 'MA' => '200'];

krsort($replace);

foreach ($strings as $str) {
    echo $str . ':' . str_replace(array_keys($replace), $replace, $str) . PHP_EOL;
}

// 1000-M => 1000-500
// 1000-MA => 1000-200
// 1000+MA-M => 1000+200-500
// MA/2 => 200/2
// M*MA+100 => 500*200+100

Example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading