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
https://forums.phpfreaks.com/topic/183925-simple-regex-is-this-correct/
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);


?>

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.