Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.
That, with the limited knowledge that I have, can be easily done in two different ways in PHP. Like this:
<?php
$some_code = '<a href="#test">Test</a>';
echo '<pre><code>' . htmlspecialchars( $some_code, ENT_QUOTES ) . '</code></pre>';
?>
Or this way:
<?php
$some_code = '<a href="#test">Test</a>';
echo '<pre><code>' . str_replace( array('<', '>', '&', '\'', '"'), array('<', '>', '&', ''', '"'), $some_code ) . '</code></pre>';
?>
(That's just to show you what I am trying to do, and not how I am doing it in reality. For example, the $some_code
is provided dynamically, not manually.)
Not considering how much easier it is to simply use htmlspecialchars()
over str_replace()
, which one of the two would be a better choice for what I am trying to do? (In terms of performance, that is.)
Okay, I see that this needs more context. This is what I am actually trying to do:
<?php
$some_code = '<a href="#test">Test</a>';
echo '<pre><code>' . str_replace(
// Replace these special characters
array( '<', '>', '&', '\'', '"', '‘', '’', '“', '”', '/', '[', ']' ),
// With the HTML entities below, respectively
array('<', '>', '&', ''', '"', ''', ''', '"', '"', '"', '/', '[', ']'),
$some_code
) . '</code></pre>';
?>
VERSUS:
<?php
$some_code = '<a href="#test">Test</a>';
return '<pre><code>' . str_replace(
array( '‘', '’', '“', '”', '/', '[', ']' ),
array(''', ''', '"', '"', '"', '/', '[', ']'),
htmlspecialchars( $content, ENT_QUOTES )
) . '</code></pre>';
?>
You should move &
and &
to the start of each array to avoid double-escaping. After that, I’d suggest using just str_replace
, since it makes what you’re trying to do more obvious (to me, anyways — nested function calls can be confusing!) but it’s really up to you. The performance difference won’t be noticeable; a string that big would cause other problems.