替换另一个字符串中的确切字符串

huangapple go评论95阅读模式
英文:

replace exact string in another string

问题

我有一个变量数组

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

以及字符串 "1000-M", "1000-MA", "1000+MA-M", "MA/2", "M*MA+100"

我需要将M替换为值500,将MA替换为值200。当我使用str_replace时,它只适用于M,因为它仍然与第一个变量M匹配。

感谢帮助。

英文:

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

Thanks for help

答案1

得分: 0

你可以使用 preg_replace_callback() 函数来使用正则表达式匹配变量名。

foreach ($strings as &$str) {
  $str = preg_replace_callback('/\b(M|MA)\b/', function ($matches) use ($array) {
    return $array[$matches[1]];
  }, $str);
}
英文:

You can use preg_replace_callback() function to match the variable names using regex.

foreach ($strings as &$str) {
  $str = preg_replace_callback('/\b(M|MA)\b/', function ($matches) use ($array) {
    return $array[$matches[1]];
  }, $str);
}

答案2

得分: 0

$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
英文:

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

huangapple
  • 本文由 发表于 2023年3月10日 01:19:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定