Preg?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Preg?

Post 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
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post 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)
&#123;
	// The text that was matched
	print $matches&#1111;1];

	// Return this so we don't alter the data
	return $matches&#1111;0];
&#125;

?>
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post 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>"??
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post 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)
&#123;
	$left = '<p>';
	$right = '<\/p>';

	if (preg_match("/$left.*$right/iUs", $matches&#1111;1], $more_matches))
	&#123;
		print htmlentities($more_matches&#1111;0]);
	&#125;

	return $matches&#1111;0];
&#125;

?>
Post Reply