Page 1 of 1

preg_replace... not working!

Posted: Sat Sep 10, 2005 8:06 am
by Ree
Again me struggling with regex. Here's a little script I wrote for testing:

Code: Select all

<?php

$template = file_get_contents('del_service.htm');

function replaceTagContents($tag, $replacement, $template)
{
  $tag_start = '<'. $tag . '>';
  $tag_end = '</'. $tag . '>';
  $pattern = '#' . $tag_start . '(.*)' . $tag_end . '#s';
  $template = preg_replace($pattern, $tag_start . $replacement . $tag_end, $template);
  return $template;
}

echo replaceTagContents('ItemValue', 'BOOOH', $template);

?>
Here's the del_service.htm:

Code: Select all

<SomeStuff>Some Stuff</SomeStuff>

<ItemValue>

Item Name

</ItemValue>

<SomeStuff>Some Stuff</SomeStuff>

<ItemValue>Item Name</ItemValue>

<SomeStuff>Some Stuff</SomeStuff>
When I run the script I get this

Code: Select all

<SomeStuff>Some Stuff</SomeStuff>

<ItemValue>BOOOH</ItemValue>

<SomeStuff>Some Stuff</SomeStuff>
but I thought I would get

Code: Select all

<SomeStuff>Some Stuff</SomeStuff>

<ItemValue>BOOOH</ItemValue>

<SomeStuff>Some Stuff</SomeStuff>

<ItemValue>BOOOH</ItemValue>

<SomeStuff>Some Stuff</SomeStuff>
Why is that so?

Posted: Sat Sep 10, 2005 8:10 am
by feyd
.* by default is greedy, it will use as much space as possible to match the pattern given.
.*? by default is ungreedy, it will use as little space as possible to match the pattern given

alternately, using the U pattern modifier will reverse those roles.

Posted: Sat Sep 10, 2005 8:31 am
by Ree
Works fine now, thanks for the tip. :D

Posted: Mon Sep 12, 2005 8:40 am
by superhuang
thanks for the tip。
多谢指点!