Preg_Match Question

I am tired of searching. I have a string “<!-- Top 5 Leaderboard –><div id=“leaderboard”>Top 5 Leaderboard</div><!-- /Top 5 Leaderboard –>”

I would like to extract contents between “<!-- Top 5 Leaderboard –>” and “<!-- /Top 5 Leaderboard –>”

Can anyone help me What pattern should I use?

Hi,

Parsing HTML with a regular expression is almost never a good idea.

That said, try this:

$matches = null;
$returnValue = preg_match('/-->(.*)<!--/', '<!-- Top 5 Leaderboard --><div id="leaderboard">Top 5 Leaderboard</div><!-- /Top 5 Leaderboard -->', $matches);
print_r($matches);

Just changed a little bit to suit my requirements but getting error.


$source ='<!-- Top 5 Leaderboard --><div id="leaderboard">Top 5 Leaderboard adfasfadf ILX (New for 2013!)
Overview: The least expensive route to Hondas premium-label goodness
Drivetrain: Two four-cylinder engines to choose from as well as a gas-electric hybrid front-wheel-drive only
</div><!-- /Top 5 Leaderboard -->';
$matches = null;$returnValue = preg_match('/<!-- Top 5 Leaderboard(.*)</div><!--/', $source, $matches);print_r($matches);

Yo need to escape the slash in the closing </div> tag and make sure that the string doesn’t contain any line breaks (or use the multi-line modifier).

E.g.

/<!-- Top 5 Leaderboard(.*)<\\/div><!--/

Already tried but receiving error.

[COLOR=#007700][FONT=monospace]

[/FONT][/COLOR]Warning: preg_match(): Unknown modifier ‘<’ in C:\xampp\htdocs\ est.php on line xx[COLOR=#007700][FONT=monospace]

[/FONT][/COLOR]

This is my final code but same error

$source ='<!-- Top 5 Leaderboard –><div id=“leaderboard”>adfasfadf ILX (New for 2013!)

Overview: The least expensive route to Hondas premium-label goodness

Drivetrain: Two four-cylinder engines to choose from as well as a gas-electric hybrid front-wheel-drive only

</div><!-- /Top 5 Leaderboard –>';

$matches = null;
$returnValue = preg_match(‘<!-- Top 5 Leaderboard –>(.)<\/div><!/‘, $source, $matches);
//$returnValue = preg_match(’<!-- Top 5 Leaderboard –>(.
)<!-- \/Top 5 Leaderboard –>/’, $source, $matches);
print_r($matches);

Hi there,

Try this:

<?php
$source ='<!-- Top 5 Leaderboard --><div id="leaderboard">adfasfadf ILX (New for 2013!)


Overview: The least expensive route to Hondas premium-label goodness


Drivetrain: Two four-cylinder engines to choose from as well as a gas-electric hybrid front-wheel-drive only


</div><!-- /Top 5 Leaderboard -->';


$pattern = '/<!-- Top 5 Leaderboard -->(.*)<!-- \\/Top 5 Leaderboard -->/s';
preg_match($pattern, $source, $matches);
echo htmlspecialchars($matches[1]);
?>

By default the fullstop doesn’t match a newline character and you have to use the s modifier to force it to.

Thanks, it worked.