Page 1 of 1
Preg?
Posted: Sun Jul 21, 2002 9:29 pm
by hob_goblin
How would I look through a file on my site, and when it matches something, start grabbing, and end when it finds something else
Im trying to grab some simple things from my WebAlizer.. the daily hits.. etc
Posted: Mon Jul 22, 2002 12:38 am
by gnu2php
It partly depends on what you mean by "grabbing." What exactly do you want to grab?
However, something like this might work:
Code: Select all
<?php
$start = 'Hello';
$end = 'World';
preg_replace_callback("/$start(.*)$end/U", 'callback_func', "Hello to the World");
// The U modifier makes the search not "greedy"
function callback_func($matches)
{
// The text that was matched
print $matchesї1];
// Return this so we don't alter the data
return $matchesї0];
}
?>
Posted: Mon Jul 22, 2002 8:42 am
by hob_goblin
i have the contents of the file read into the variable $contents
now if the file contained
Code: Select all
<html>
<body>
<!-- something -->
<p>foo bar</p>
<!-- something else -->
</body>
</html>
now if $start was "<p>", and $end was "</p>", how would i return the "<p>foo bar</p>"??
Posted: Mon Jul 22, 2002 1:12 pm
by gnu2php
You can do it by searching for <p>foo bar</p> inside the callback function, like this:
Code: Select all
<?php
$data = <<<END
<html>
<body>
<!-- something -->
<p>foo bar</p>
<!-- something else -->
</body>
</html>
END;
$start = '<!-- something -->';
$end = '<!-- something else -->';
preg_replace_callback("/$start(.*)$end/iUs", 'callback_func', $data);
/*
i = ignore case
s = have newlines included in .* (should've done this anyway, sorry)
*/
function callback_func($matches)
{
$left = '<p>';
$right = '<\/p>';
if (preg_match("/$left.*$right/iUs", $matchesї1], $more_matches))
{
print htmlentities($more_matchesї0]);
}
return $matchesї0];
}
?>