Quotes in a php var -
i quite new in php. have store img tag in var. think ok:
$fototag1 = "<img src='42.png' alt='text alt'>";
but problem comes if there single quote in name of photo or in alt?. intance, don't
what have tried:
$fototag1 = "<img src='don't.svg' alt='don't>'"; echo htmlspecialchars ($fototag1); echo addslashes($fototag1); $fototag2 = "<img src='don\'t.svg' alt='don\'t'>"; echo $fototag2;
(this simplified example url , alt comes sql database , of course, cannot change text manually. need general solution)
$fototag1 = "<img src='don't.svg' alt='don't>'";
your problem here has nothing php.
you have html attribute value delimited apostrophe characters , want use apostrophe inside value.
when want represent character special meaning in html raw character, can use character reference.
this can named entity ('
) or 1 of numeric references position of character in unicode ('
);
<img src='don't.svg' alt='don't'>
beware: '
added html relatively late. old versions of ie not support it.
alternatively change html use double quotes delimit data:
<img src="don't.svg" alt="don't">
this introduce php problem because using them delimit string literal.
in case need escape data php, backslash character.
$fototag1 = "<img src=\"don't.svg\" alt=\"don't\">";
alternatively, use other form of string generation, such heredoc.
$fototag1 = <<<end <img src="don't.svg" alt="don't"> end;
as rule of thumb, better avoid storing html in variables in first place.
when want output data, switch output mode:
?> <img src="don't.svg" alt="don't"> <?php
you can drop php mode if need variable.
$src = "don't.svg"; $alt = "don't"; ?> <img src="<?php echo htmlspecialchars($src); ?>" alt="<?php echo htmlspecialchars($alt); ?>"> <?php
(note characters involved, htmlspecialchars
isn't needed in example, protect when dealing programmatically acquired data can't guarantee html safe).
Comments
Post a Comment