foreach在正则表达式?

时间:2010-07-16 12:44:14

标签: php regex

  

可能重复:
  php regular expression help?

喜 我想替换

i like apple
apple is good
orange is also nice
my mom likes banana
apple 123 4
the pear is soo sweat
my dad loves pear

i like apple
apple is good
orange is also nice
my mom likes banana
apple 1
apple 2
apple 3
apple 4
the pear is soo sweat
my dad loves pear

by preg_replace?

1 个答案:

答案 0 :(得分:1)

<?
function replace($matches)
{
        return preg_replace("/\s*(\d)\s*/", "$matches[1] $1\n", $matches[2]);
}
$s = "i like apple
apple is good
orange is also nice
my mom likes banana
apple 123 4
the pear is soo sweat
my dad loves pear";
echo "Before::......\n\n$s\n\nAfter::......\n\n";
echo preg_replace_callback('/^(apple) ([\d ]+)\n/m', 'replace', $s);
echo "\n";
?>

输出:

Before::......

i like apple
apple is good
orange is also nice
my mom likes banana
apple 123 4
the pear is soo sweat
my dad loves pear

After::......

i like apple
apple is good
orange is also nice
my mom likes banana
apple 1
apple 2
apple 3
apple 4
the pear is soo sweat
my dad loves pear