Any questions involving matching text strings to patterns - the pattern is called a "regular expression."
Moderator: General Moderators
Ree
Forum Regular
Posts: 592 Joined: Fri Jun 10, 2005 1:43 am
Location: LT
Post
by Ree » Fri Sep 09, 2005 2:56 am
Have a look at this:
Code: Select all
function GetTagContents($tag)
{
$tag_start = '<'. $tag . '>';
$tag_end = '</'. $tag . '>';
$pattern = '#' . $tag_start . '(.*)' . $tag_end . '#';
preg_match($pattern, $this->template, $matches);
return $matches[1];
}
If $tag is 'body', the function should return whatever the tag contains, for example if $this->template contains '<body>blah</body>', the function should return 'blah'. But I get 'Notice: Undefined offset: 1 in the script'. How come? I thought $matches[0] would be '<body>blah</body>', and $matches[1] - 'blah'. No?
anjanesh
DevNet Resident
Posts: 1679 Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India
Post
by anjanesh » Fri Sep 09, 2005 4:32 am
Code: Select all
<?php
echo GetTagContents("<body>test</body>","body");
function GetTagContents($template, $tag)
{
$tag_start = '<'. $tag . '>';
$tag_end = '</'. $tag . '>';
$pattern = '#' . $tag_start . '(.*)' . $tag_end . '#';
preg_match($pattern, $template, $matches);
return $matches[1];
}
?>
is returning
test
Ree
Forum Regular
Posts: 592 Joined: Fri Jun 10, 2005 1:43 am
Location: LT
Post
by Ree » Fri Sep 09, 2005 6:53 am
Yeah, that returns what's expected. But actually, the string I get from a file. I wrote a simple test script:
Code: Select all
<?php
$string = file_get_contents('test.htm');
$tag = 'ServiceList';
$tag_start = '<'. $tag . '>';
$tag_end = '</'. $tag . '>';
$pattern = '#' . $tag_start . '(.*)' . $tag_end . '#';
preg_match($pattern, $string, $matches);
echo $matches[1]; //Notice: Undefined offset: 1 in ...
?>
Here's the test.htm:
Code: Select all
<ServiceList>
<tr>
Stuff
</tr>
</ServiceList>
And I get that notice and no output.
What am I missing?
anjanesh
DevNet Resident
Posts: 1679 Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India
Post
by anjanesh » Fri Sep 09, 2005 7:15 am
Code: Select all
$pattern = '#' . $tag_start . '(.*)' . $tag_end . '#is';
Ree
Forum Regular
Posts: 592 Joined: Fri Jun 10, 2005 1:43 am
Location: LT
Post
by Ree » Fri Sep 09, 2005 7:22 am
Thanks, that newline modifier I was not aware of.
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Fri Sep 09, 2005 8:55 am
tip: use preg_quote on the $tag_start and $tag_end variables too.