Place an HTML tag on the </body> using string (PHP)

Asked

Viewed 1,027 times

1

Hello I am making a software to send Emails in PHP. One has a form and she sends HTML by a link. But here I will put a simple HTML.

$texto = "<!DOCTYPE HTML>
<html lang='pt-br'>
<head>
 <meta charset='UTF-8'>
 <link rel='stylesheet' type='text/css' href='estilo.css'>
 <title></title>
</head>
<body>
<!--conteúdo do BODY -->
<!--Tag a ser inserida -->
</body>
</html>";

What I want is to insert a tag at the end of the tag body before the /body.

<table class="dashedBorder" width="100%" cellspacing="0" cellpadding="0" border="0" align="center" style="width: 550">
<tbody>
<tr>
<td valign="middle" align="center" style="FONT-FAMILY: Arial; WHITE-SPACE: normal; FONT-SIZE: 11px">
<font color="#444444">Esse email foi enviado para [email protected] para parar de receber e-mails clique <a href="">aqui</a> </font>
</td>
</tr>
<tr> </tr>
<tr>
</tbody>
</table>

How can I do this in PHP? Taking into account that every file in the $text will have a /body within the variable?

2 answers

3


Use the function str_replace which is used to replace one part of the text with another in a string. For example, in your case:

$textoAdicional = '<table>...</table>';
$texto = str_replace('</body>', $textoAdicional . '</body>', $texto);

In this way, I am substituting in the variable $texto the string </body> for <table>...</table></body>.

2

Use the htmlspecialchars() to print the text:

echo htmlspecialchars($texto);

This function will escape all HTML special characters.


One detail, your PHP code is invalid, because you are opening the string using double quotes and in the middle of the text you are closing it, using double quotes, even if this is not your intention. The correct would be to use single quotes inside the HTML. Example:

$texto = "<!DOCTYPE HTML>
<html lang='pt-br'>
<head>
  <meta charset='UTF-8'>
  <link rel='stylesheet' type='text/css' href='estilo.css'>
  <title></title>
</head>
<body>
<!--conteúdo do BODY -->
<!--Tag a ser inserida -->
</body>
</html>";

So you don’t have to worry about the quotes, use Heredoc in creating your strings, see how it looks better and elegant:

$texto = <<<EOD
<!DOCTYPE HTML>
<html lang="pt-br">
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="estilo.css">
  <title></title>
</head>
<body>
<!--conteúdo do BODY -->
<!--Tag a ser inserida -->
</body>
</html>
EOD;
  • Why you showed how to display the text?

  • But this function gives support to replace the HTML string in addition to printing it?

  • I failed to understand the question, the @Oeslei solution is what you need. I thought you wanted to print HTML in text.

  • All right, your answer is very useful despite this. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.