Isaac Bosca Isaac Bosca - 3 months ago 12
HTML Question

How to delete some text from HTML using PHP

I have an HTML like this into a PHP variable called

$html
:



<html>
<head>
<title>MyPage</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>MyPage</h1>
<h2>{SUBTITLE}</h2>
<div>{BODY}</div>
</body>
</html>





I need to delete the tag and the contents inside the tag, if inside the tag only appears
{something}
. For example, in this case, the lines:

<h2>{SUBTITLE}</h2>
<div>{BODY}</div>


Must be deleted.

I was thinking in something like that:

$html = str_replace('{'%%'}', '', $html);


This line doesn't work, but what I try to do it's, replace words that starts and ends by '{' and '}' with nothing (I don't know how to do it), and the other problem is how to delete the empty tags as well.

Answer

You could use a regular expression.

Your regular expression could look like this:

<\w*>{\w*}<\/\w*>

This searches for a starting <, followed by 1-n literals or numbers, followed by >. Then followed by {, 1-n literals or numbers,}, </, 1-n literals or numbers and finally the closing >

$html = preg_replace('/<\w*>{\w*}<\/\w*>/', '', $html);

This would not only replace the content, but remove the tags themselves as well.