preg_match problemo

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_match problemo

Post by Ree »

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?
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

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 »

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?
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

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 »

Thanks, that newline modifier I was not aware of.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

tip: use preg_quote on the $tag_start and $tag_end variables too.
Post Reply