PHP making first letter an image
I need an HTML-safe function which will change a first letter of the content to the image source.
So if my content will be: "Hello World!
" the开发者_JS百科 output will look like:
"<img src="/images/letters/H.png" alt="H"/>ello"
I've tried something like:
$content = '<img src="/images/letters/'.$content[0].'.png" />'.substr($content, 1);
But I've heard this way isn't safe for HTML due to characters like <
and >
.
$content = '<img src="/images/letters/'.$content[0].'.png" />'.substr($content, 1);
will work just fine, it will always be truncated to 1 character, so as long as you have no sensitive files in that directory named _.png or something, you're fine. To ensure your page doesn't break:
$alph = "abcdefghijklmnopqrstuvwxyz";
if (strpos($alph,$content[0])) {
$content = '<img src="/images/letters/'.$content[0].'.png" />'.substr($content, 1);
}
$content = preg_replace("/^([a-z])/i","<img src=\"/images/letters/$1.png\" alt=\"$1\" />",$content);
Are you worried about creating a broken image? How about:
$first_letter = $content[0];
// A <= $first_letter <= Z
if(('A' <= $first_letter ) && ($first_letter <= 'Z')) {
$content = '<img src="/images/letters/' . $first_letter . '.png" />'.substr($content, 1);
}
精彩评论