regex: how to replace a group of tags as a whole?
I want to replace all meta tags with a set of new meta tags. I have the following code
<?php
$header = '
<link rel="shortcut icon" href="/images/favicon.ico" />
<title>meta replace test</title>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="..." />
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="script.js"></script>';
$meta = '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="content-language" content="en" />
<meta http-equiv="imagetoolbar" co开发者_JAVA百科ntent="no" />
<meta name="resource-type" content="document" />
<meta name="distribution" content="global" />
<meta name="copyright" content="2000, 2002, 2005, 2007 phpBB Group" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9" />';
$regex = '/<meta.*\/>/';
preg_match_all($regex, $header, $matches);
$header = preg_replace($regex, $meta, $header);
echo "<pre>";
echo print_r($matches);
echo "</pre>";
the meta tags in the $header
should be replaced with the meta tags from $meta
. There are 3 meta tags in the $header
so it will replace 3 times unless I put all the meta tags next to eachother. I only want to replace once, no matter how many tags there are.
The regex I use is the following:
$regex = '/<meta.*\/>/';
If you want to replace all the <meta...>
tags with the contents of $meta
, you’ll have to remove the tags as a separate step, and then insert your replacement at a particular point.
This solution requires that the tags are in a well-formed format. Note that it hasn’t been tested.
$header = preg_replace(/<meta\s.*?\/>/isg, "", $header);
$header = preg_replace(/(<\/title>[\s\n]*)/is, "$1$meta", $header);
精彩评论