Jump to content

Need help with preg Functions to make a Header & Footer


SupraCharger

Recommended Posts

Hi,

  I'm trying to pull out parts of a html page and I've tried this for hours an I can't seem to get it to work.

 

// I'm pulling this info from get_file_contents ()
$contfile = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<!-- PHP: Header End -->

<!-- PHP: Footer Start -->
</body>
</html>
';

$pattern = '/^(.*)(<!\-\- PHP: Header End \-\->)(.*)$/';
$replacement = "$1$2";

$header = preg_replace ($pattern, $replacement, $contfile);
 

 

// I want it to output
$header = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<!-- PHP: Header End -->
';
 

 

I've tried to use other functions (preg_grep () , preg_match () ) and I can't get those to work. If you could please show me the syntax to how to properly accomplish this task It would be greatly appreciated.

 

Thanx for your help,

Andrew

The simpler version of that expressions would be as follows:

$RegExp = '/^.*?PHP: Header End -->/us';
"u" to make sure it's UTF-8 compatible, and "s" to make the dot match newlines as well.

 

Hyphens only have a special meaning inside a character class, and the greater-than sign only in named groups and lookarounds. Of course, if in doubt it doesn't really hurt to escape them.

 

Of course, that said this could have been done quite simply with a strpos and substr combination.

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.