How to remove <br> within a <textarea></textarea> only
I have some articles stored in a text field in my database. There are times when the article includes <textarea>content.....</textarea>
The problem is that when the content is displayed on a page using php, it includes the actual <br><br><br&g开发者_运维百科t;
. The <br>
is placed there by the text editor (CKEditor)
So it looks like the following
<textarea>
<-- this actually becomes a textareaThis content is shown inside the text area
<br>
but the problem is that the<br>
is also shown.</textarea>
How can I strip <br>
from the <textarea>
tags only. I imagine some preg replace would be useful.
Your best bet is to use an HTML parser to do it:
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('textarea') as $textarea) {
foreach ($textarea->childNodes as $child) {
if ($child->nodeName == 'br') {
$textarea->removeChild($child);
}
}
}
$content = $dom->saveHTML();
Basically regexes are a poor tool for processing HTML because HTML isn't "regular" in the sense of "regular expression". This means it doesn't handle things like nested elements without using an unreliable hack.
$x='<br><textarea>abcd<br>efgh</textarea><br><br>';
echo preg_replace('/<textarea>.*?<\/textarea>/e','str_replace("<br>","","\\0")',$x);
//<br><textarea>abcdefgh</textarea><br><br>
If you using <br />
, please update it appropriately.
here's one way
$str= <<<A
<textarea> <-- this actually becomes a textarea
This content is shown inside the text area<br> but the problem is that the <br> is also shown. </textarea>
A;
$s = explode("</textarea>",$str);
for($i=0;$i<count($s)-1;$i++){
if(strpos($s[$i],"<textarea>")!==FALSE){
$s[$i] = preg_replace("/<br>/","",$s[$i]);
}
}
print implode("</textarea>",$s);
Have you had a look at what the database is storing - maybe it's HTMLencoding it before writing to the database and so what you're seeing is actually :
<br />
This can happen when you use fields generated by CKEditor and TinyMCE as it escapes fields before $_POSTing
Given the HTML...
<textarea id="text">Some text here.<br>Some other text.</textarea>
...perform this Javascript...
document.getElementById('text').value = document.getElementById('text').value.replace(/<br>/g,'\r');
finally i found the answer it is so strange.. but it fixed the problem.
as i notice.. if we write line 1 line2 line3
it actually write a the content with multi line and without
or or whatever
so i do the following function
function clear_string($string) {
$string = str_replace(array('\r\n', '\r', '\n'), '
', $string);
return $string;
}
and i use it whenever i want to save the content of textarea and save it on variable, also i can know easily echo the value of the variable for the textarea ... for example
<textarea><?php echo $notes;?> </textarea>
thank you so much for your help
and i hope it helps people who face same problem
精彩评论