我有一个立陶宛语词形变化的代码:
<?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);
}
?>
像循环一样思考,
- 将
as
更改为as
,字符串变为'namas-namas' - 将
as
更改为o
,字符串变为'namo namo namo' - 将
as
更改为ui
,并且没有匹配(保留"namo namo namo'") - 将
as
更改为o
,并且没有匹配(保留"namo namo namo'")