preg_replace... not working!

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

preg_replace... not working!

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post by Ree »

Works fine now, thanks for the tip. :D
User avatar
superhuang
Forum Newbie
Posts: 3
Joined: Mon Sep 12, 2005 8:22 am

Post by superhuang »

thanks for the tip。
多谢指点!
Post Reply