Jump to content

Simple Regex. Is this correct?


bundyxc

Recommended Posts

I'm looking throughout an entire HTML document for something in this format:

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title><!--{template:title}--></title>
<link rel="stylesheet" type="text/css" href="my.css">
</head>
<body>
    <h1><!--{template:header}--></h1>
    <p><!--{template:paragraph}--></p>
</body>
</html>

 

I'd like to look through the file, and have matches of: title, header, paragraph. What's the code I would use to do this? I was using this:

\<!--{template:(.*)}-->

 

But unfortunately, that simply matches the entire HTML comments. I'm assuming that this has to do with lookarounds. Any suggestions?

Link to comment
Share on other sites

try this

 

<?php   
$str = <<< EOS
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
   <title><!--{template:title}--></title>
   <link rel="stylesheet" type="text/css" href="my.css">
</head>
<body>
    <h1><!--{template:header}--></h1>
    <p><!--{template:paragraph}--></p>
</body>

EOS;

preg_match_all('#\{template:(.*?)\}#', $str, $matches);

print_r($matches);


?>

Link to comment
Share on other sites

What do you mean "it matches the entire comment?" The part in the brackets is the first capture group and can be found in the array $matches[1]. It can be done with lookbehind and lookahead assertions, but do you really need to?

 

The pattern would turn into something along the lines of... but you should probably avoid using the fullstop if only certain characters are valid (such as letters only). Also some of these characters may well need escaping, I'm not on a computer I can test it with atm.

 

#(?<=<!--{template:)(.*)(?=}-->)#isU

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.