如何在PHP中以不同的方式替换相同的值



我有一个立陶宛语词形变化的代码:

<?php
    $word               = "namas";
    $string             = str_repeat("$word ", 4);
    $patterns           = array();
    $patterns[0]        = '/as/';
    $patterns[1]        = '/as/';
    $patterns[2]        = '/as/';
    $patterns[3]        = '/as/';
    $replacements       = array();
    $replacements[0]    = 'as';
    $replacements[1]    = 'o';
    $replacements[2]    = 'ui';
    $replacements[3]    = 'a';
    ksort($patterns);
    ksort($replacements);
    echo preg_replace($patterns, $replacements, $string);
?>

我怎么能用不同的方式替换?我希望有这样的结果:namas namui nama但我在任何地方都有"namo namo"。

这就是我认为你想要的:

<?php
$word ="namas";
$patterns = array();
$patterns[0] = '/as/';
$patterns[1] = '/as/';
$patterns[2] = '/as/';
$patterns[3] = '/as/';
$replacements = array();
$replacements[0] = 'as';
$replacements[1] = 'o';
$replacements[2] = 'ui';
$replacements[3] = 'a';
ksort($patterns);
ksort($replacements);
foreach ($patterns as $idx => $pat)
{
    echo " " . preg_replace ($pat, $replacements[$idx], $word);
}
?>

它被进一步简化为:

<?php
$word ="namas";
$pattern = '/as/';
$replacements = array();
$replacements[0] = 'as';
$replacements[1] = 'o';
$replacements[2] = 'ui';
$replacements[3] = 'a';
foreach ($replacements as $replace)
{
    echo " " . preg_replace ($pattern, $replace, $word);
}
?>  

像循环一样思考,

  1. as更改为as,字符串变为'namas-namas'
  2. as更改为o,字符串变为'namo namo namo'
  3. as更改为ui,并且没有匹配(保留"namo namo namo'"
  4. as更改为o,并且没有匹配(保留"namo namo namo'"

相关内容

  • 没有找到相关文章

最新更新