Jump to content

escaping html tags for a textarea


cooldude832

Recommended Posts

I'm trying to escape html tags so I can put them in a textarea with out having a </textarea> stop the text area

example

<?php
$var = "<P><textarea name\"var1\">Blah</textarea>";
echo "<textarea name=\"update\">".$var."</textarea>";
?>

 

But because $var has a </textarea> in it it breaks the textarea there instead of later

Link to comment
https://forums.phpfreaks.com/topic/118400-escaping-html-tags-for-a-textarea/
Share on other sites

<?php
function textarea ($str) {
    $open = '<textarea>';
    $close = '</textarea>';

    // Count the opening tags
    preg_match_all ('/\[textarea\]/i', $str, $matches);
    $opentags = count($matches['0']);

    // Count the close tags
    preg_match_all ('/\[\/textarea\]/i', $str, $matches);
    $closetags = count($matches['0']);

    // reiterate through loop to close all the open tags, there's probably a more elegant way of doing this
    $unclosed = $opentags - $closetags;
    for ($i = 0; $i < $unclosed; $i++) {
        $str .= $close;
    }

    // Do replacement
    $str = str_replace ('[textarea]', $open, $str);
    $str = str_replace ('[/textarea]', $close, $str);

    return $str;
}
?>

<?php
function textarea ($str) {
    $open = '<textarea>';
    $close = '</textarea>';

    // Count the opening tags
    preg_match_all ('/\[textarea\]/i', $str, $matches);
    $opentags = count($matches['0']);

    // Count the close tags
    preg_match_all ('/\[\/textarea\]/i', $str, $matches);
    $closetags = count($matches['0']);

    // reiterate through loop to close all the open tags, there's probably a more elegant way of doing this
    $unclosed = $opentags - $closetags;
    for ($i = 0; $i < $unclosed; $i++) {
        $str .= $close;
    }

    // Do replacement
    $str = str_replace ('[textarea]', $open, $str);
    $str = str_replace ('[/textarea]', $close, $str);

    return $str;
}
?>

 

You could still end up with

 

<textarea>stuff blah</textarea>hahahaahahahah<textarea></textarea></textarea>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.