11

Basically I want to turn a string like this:

<code> &lt;div&gt; blabla &lt;/div&gt; </code>

into this:

&lt;code&gt; <div> blabla </div> &lt;/code&gt;

How can I do it?


The use case (bc some people were curious):

A page like this with a list of allowed HTML tags and examples. For example, <code> is a allowed tag, and this would be the sample:

<code>&lt;?php echo "Hello World!"; ?&gt;</code>

I wanted a reverse function because there are many such tags with samples that I store them all into a array which I iterate in one loop, instead of handling each one individually...

2
  • 1
    Will the source string always be in the same format: an HTML entity-encoded string wrapped in <code> tags? Or do you require a solution that can handle more generic situations, where encoded and non-encoded characters may be mixed?
    – Mike
    Jul 16, 2011 at 15:23
  • Interesting indeed. Could you provide a use case? Just curious...
    – aercolino
    Jul 18, 2011 at 13:28

7 Answers 7

4

My version using regular expressions:

$string = '<code> &lt;div&gt; blabla &lt;/div&gt; </code>';
$new_string = preg_replace(
    '/(.*?)(<.*?>|$)/se', 
    'html_entity_decode("$1").htmlentities("$2")', 
    $string
);

It tries to match every tag and textnode and then apply htmlentities and html_entity_decode respectively.

2
  • thank you. I don't know which method should I go with, yours or adlawson's :)
    – Alex
    Jul 18, 2011 at 13:43
  • @Alex You are welcome! Both methods has its own side effects. You need to test which works the best in your case.
    – Karolis
    Jul 18, 2011 at 18:48
4
+200

There isn't an existing function, but have a look at this. So far I've only tested it on your example, but this function should work on all htmlentities

function html_entity_invert($string) {
    $matches = $store = array();
    preg_match_all('/(&(#?\w){2,6};)/', $string, $matches, PREG_SET_ORDER);

    foreach ($matches as $i => $match) {
        $key = '__STORED_ENTITY_' . $i . '__';
        $store[$key] = html_entity_decode($match[0]);
        $string = str_replace($match[0], $key, $string);
    }

    return str_replace(array_keys($store), $store, htmlentities($string));
}

Update:

  • Thanks to @Mike for taking the time to test my function with other strings. I've updated my regex from /(\&(.+)\;)/ to /(\&([^\&\;]+)\;)/ which should take care of the issue he raised.

  • I've also added {2,6} to limit the length of each match to reduce the possibility of false positives.

  • Changed regex from /(\&([^\&\;]+){2,6}\;)/ to /(&([^&;]+){2,6};)/ to remove unnecessary excaping.

  • Whooa, brainwave! Changed the regex from /(&([^&;]+){2,6};)/ to /(&(#?\w){2,6};)/ to reduce probability of false positives even further!

6
  • adlawson++ That is a really neat solution.
    – Mike
    Jul 16, 2011 at 19:12
  • You can do the same inversion in one step using very similar code to mine.
    – Karolis
    Jul 17, 2011 at 14:46
  • I'm not sure how you would achieve the same result. The closest I've come is using return preg_replace('/(&(#?\w){2,6};)([^&;]*)/', html_entity_decode("$1") . htmlentities("$2"), $string);, but it doesn't work. It's much more simple to tackle each problem separately than with a single regex.
    – adlawson
    Jul 17, 2011 at 15:05
  • 1
    @adlawson Why do you think regex is much more difficult? By the way you use regex too :) The common problem about regex is readability. But in this case regex is short and even faster. For instance all your code can be rewritten as this: return preg_replace('/(.*?)(&(#?\w){2,6};|$)/se', 'htmlentities("$1").html_entity_decode("$2")', $string);
    – Karolis
    Jul 17, 2011 at 16:04
  • By the way &(#?\w){2,6}; is not very good for matching html entity because it will match &ab#cd;, but it will not match &thetasym;. I think &#?\w+; or something similar would be better.
    – Karolis
    Jul 17, 2011 at 16:12
1

Replacing alone will not be good enough for you. Whether it be regular expressions or simple string replacing, because if you replace the &lt &gt signs then the < and > signs or vice versa you will end up with one encoding/decoding (all &lt and &gt or all < and > signs).

So if you want to do this, you will have to parse out one set (I chose to replace with a place holder) do a replace then put them back in and do another replace.

$str = "<code> &lt;div&gt; blabla &lt;/div&gt; </code>";
$search = array("&lt;","&gt;",);

//place holder for &lt; and &gt;
$replace = array("[","]");

//first replace to sub out &lt; and &gt; for [ and ] respectively
$str = str_replace($search, $replace, $str);

//second replace to get rid of original < and >
$search = array("<",">");
$replace = array("&lt;","&gt;",);
$str = str_replace($search, $replace, $str);

//third replace to turn [ and ] into < and >
$search = array("[","]");
$replace = array("<",">");

$str = str_replace($search, $replace, $str);

echo $str;
3
  • I was hoping there's a built in function, or at least less code necessary to accomplish this. I don't like the idea of handling the conversion for each character...
    – Alex
    Jul 15, 2011 at 15:04
  • If there is a built-in function, I do not know what it is. You could just make this a function, and call it whenever you need it with the string as a parameter. It really isn't that much code, and all of the operations would be quick. I think your desire is a little to specific for a built-in function, but then that is the point of user defined functions.
    – Aaron Ray
    Jul 15, 2011 at 17:40
  • 2
    There would not be a built-in function for this because, as interesting as the question is, I can't see any use case here that isn't either a complete edge case, theoretical, or a horrid code smell. Jul 16, 2011 at 18:08
1

I think i have a small sollution, why not break html tags into an array and then compare and change if needed?

function invertHTML($str) {
    $res = array();
    for ($i=0, $j=0; $i < strlen($str); $i++) { 
        if ($str{$i} == "<") { 
           if (isset($res[$j]) && strlen($res[$j]) > 0){
                $j++; 
                $res[$j] = '';
           } else {
               $res[$j] = '';
           }
           $pos = strpos($str, ">", $i); 
           $res[$j] .= substr($str, $i, $pos - $i+1); 
           $i += ($pos - $i); 
           $j++;
           $res[$j] = '';
           continue; 
        } 
        $res[$j] .= $str{$i}; 
    } 

    $newString = '';
    foreach($res as $html){
        $change = html_entity_decode($html);
        if($change != $html){
            $newString .= $change;
        } else {
            $newString .= htmlentities($html);
        }
    }
    return $newString; 
}

Modified .... with no errors.

9
  • The first for loop iterates over every character in the string individually and out of context. This will break for strings like <div>5 > 1</div>. Also, its best to pass strlen($string) by reference, otherwise it recalculates the length for every iteration.
    – adlawson
    Jul 17, 2011 at 10:28
  • I've just tested it with the OP's string, and with "5 > 1", and you get Undefined offset: $i in both cases.
    – adlawson
    Jul 17, 2011 at 10:29
  • Modified, no errors, althrough .... if you test a string 10k large you will get a 2.3 times faster result from my script than with your preg_match. Jul 17, 2011 at 11:44
  • While your function may perform slightly faster, mine has the advantage of inverting any html entity (&raquo;, &mdash, &heart etc). It was the strlen in for ($i=0, $j=0; $i < strlen($str); $i++) { that I meant should be passed by reference.
    – adlawson
    Jul 17, 2011 at 11:58
  • are you sure my example doesen't convert any html entity? Jul 17, 2011 at 13:47
1

So, although other people on here have recommended regular expressions, which may be the absolute right way to go ... I wanted to post this, as it is sufficient for the question you asked.

Assuming that you are always using html'esque code:

 $str = '<code> &lt;div&gt; blabla &lt;/div&gt; </code>';
 xml_parse_into_struct(xml_parser_create(), $str, $nodes);
 $xmlArr = array();
 foreach($nodes as $node) { 
     echo htmlentities('<' . $node['tag'] . '>') . html_entity_decode($node['value']) . htmlentities('</' . $node['tag'] . '>');
 }

Gives me the following output:

&lt;CODE&gt; <div> blabla </div> &lt;/CODE&gt;

Fairly certain that this wouldn't support going backwards again .. as other solutions posted, would, in the sense of:

 $orig = '<code> &lt;div&gt; blabla &lt;/div&gt; </code>';
 $modified = '&lt;CODE&gt; <div> blabla </div> &lt;/CODE&gt;';
 $modifiedAgain = '<code> &lt;div&gt; blabla &lt;/div&gt; </code>';
0

I'd recommend using a regular expression, e.g. preg_replace():

1
  • 3
    Vomiting "REGULAR EXPRESSION!" and chucking arbitrary links on regular expressions at everybody is not an answer. Jul 16, 2011 at 18:06
0

Edit: It appears that I haven't fully answered your question. There is no built-in PHP function to do what you want, but you can do find and replace with regular expressions or even simple expressions: str_replace, preg_replace

5
  • What makes you think print will decode the entities? Also, this doesn't solve the actual problem.
    – Matt
    Jul 12, 2011 at 17:30
  • @Matt OP could also use html_entity_decode. See edit for your second remark.
    – wanovak
    Jul 12, 2011 at 17:32
  • I don't understand why you're using buffers at all. $var is the same as $out in your example.
    – Matt
    Jul 12, 2011 at 17:34
  • Didn't think it would be. Editing to remove false info.
    – wanovak
    Jul 12, 2011 at 17:36
  • 1
    This doesn't even come close to answering anything like the question. Jul 16, 2011 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.