comecomeone comecomeone - 4 months ago 20
HTML Question

how to add slashes to only double quotes

i want to add slashes to only double quotes to some html elements this is how i am doing , but its not working for me :

$str ="
<table class="body-wrap" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; width: 100%; margin: 0; padding: 0;">
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; margin: 0; padding: 0;">
<td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; margin: 0; padding: 0;">this is my test</td></tr></table>&#13;";


this is my php function :

$str2 = addcslashes($str, '"');


i think that i have problems at the beginning of my string , i dont know how to declare :

$str =" or $str = '


both for me didnt work

Answer

Delete your string $str =" or $str = ' as this is entirely wrong.

1) Use a CSS Style Sheet to store your CSS outside your HTML and avoid repetition.

2) Use single quotes in HTML syntax (and your PHP string is in double quotes) to avoid the need to escape your HTML at all (javascript elements will be an exception, however).

Example of points one and two combined:

CSS File

.body_wrap_table { 
     width: 100%; 
}
.table_td_tr {
    font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;    
      margin: 0; 
      padding: 0;
}

HTML PHP String

$str = " <table class='body-wrap body_wrap_table'>
    <tr class='table_td_tr'>
    <td class='table_td_tr'>this is my test</td></tr></table>
";

So no need for quote escaping at all.

3) If you really want to do it you can use a Regex function such as Preg_replace as exampled here:

$str = preg_replace('/"+(?<!\\")/', '\"', $str);

This regex will match any " character which is not preceeded by a \ character, and the replace with an escaped quote.

4) A possibly simpler approach which may or may not be a solution for you (and less processor heavy than a Regex) is to simply use a str_replace such as :

$str = str_replace("\"","\\\",$str); 

This replaces any text fitting the shape " with \" but this may cause double escaping if a quote already has an escape mark preceeding it.

References: