简体   繁体   中英

php echoing dynamic variable containing quotes

I have a variable $dcomment and need to do the following:

echo '<div class="commentBox">' . 
      '<span class="byText">[BY]</span> ' . 
      '<span class="commenterName"><a href=" '.$webLink.' ">'.$dname.'</a></span>' . 
      '&nbsp; [DATE] ' . $dt . '</span>' . '<br>' .
      '[COMMENT] ' . $dcomment .
      $linkdel . '<br />' . 
'</div>';

The variables may contain quotes within them, like

$dcomment = "Stackoverflow's great"; // containing single quote in it ... etc

is there any built-in php function to solve this or how can I do that?

I think you are looking for htmlentities($str) (click for manual page)

It will replace all applicable characters to HTML entities, so you don't have to fear getting " , < and similar characters in your mark-up and attribute fields.


If you want to also escape single quotes ' , use

htmlentities($str, ENT_QUOTES)

(as described in the documentation)

You could replace all quotes with their HTML entity. htmlentities or str_replace

htmlentities : http://php.net/manual/en/function.htmlentities.php

str_replace : http://php.net/manual/en/function.str-replace.php

Note : You need to use ENT_QUOTES for htmlentities .

htmlentities($dcomment, ENT_QOUTES)

To escape strings for use in HTML context, PHP provides the htmlspecialchars function. It will replace " , ' , & , < , and > with their respective HTML entities.

If you need to escape strings for use as an URL, there's the urlencode and rawurlencode functions.

Sometimes it's necessary to combine both, ie html-escape an urlencoded string.

Ok I did this and worked: [I have voted up everyone who helped me here, thank you all]

$name= mysql_real_escape_string($_POST['name']);
$emailAddress = mysql_real_escape_string($_POST['emailAddress']);
$webAddress = mysql_real_escape_string($_POST['webAddress']);
$comment=mysql_real_escape_string($_POST['comment']);
$submit=mysql_real_escape_string($_POST['submit']);

Thanks to @MightyPork :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM