Page 1 of 1

preg_match problemo

Posted: Fri Sep 09, 2005 2:56 am
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?

Posted: Fri Sep 09, 2005 4:32 am
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

Posted: Fri Sep 09, 2005 6:53 am
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?

Posted: Fri Sep 09, 2005 7:15 am
by anjanesh

Code: Select all

$pattern = '#' . $tag_start . '(.*)' . $tag_end . '#is';

Posted: Fri Sep 09, 2005 7:22 am
by Ree
Thanks, that newline modifier I was not aware of.

Posted: Fri Sep 09, 2005 8:55 am
by feyd
tip: use preg_quote on the $tag_start and $tag_end variables too.