开发者

Parsing Line Breaks in PHP/JavaScript

EDIT: Ok, thanks for your help guys. Using zerkms' suggestion, I have managed to get <br> tags inserted instead of carriage returns, so it is displayed properly on the page and doesn't break the javascript. The problem is now that when the user clicks on this text, it becomes a textarea and is therefore inline editable. However, the text string now has the tags displayed in it, rather than just having the editable text over multiple lines.

Any suggestions?

ORIGINAL QUESTION: I have a text area in my PHP application where users can enter notes in a project. Sometimes this is displayed on the page via PHP and sometimes it is displayed via javascript. The problem is, if the note is across multiple lines (i.e. the user presses enter while entering notes in the text area), it causes the JS to fail. It's fine when it's being done by the PHP.

The line of code in question is:

var editnotes='<textarea class="desc_text" style="width:20em;" id="notes_editor"><?php print $notes; ?></textarea>';

So, if the note is over multiple lines, the PHP builds the pager as:

var editnotes='<textarea class="desc_text" style="width:20em;" id="notes_editor">This is
a test note
over multiple lines
</textarea>';

And this obviously causes problems for the js. So my question is, what can I do to prevent this? As the code is being built by PHP before it even gets to the browser, I'm thinking that the best approach may be to parse it in the PHP so that the output is something more like this:

var editnotes='<textarea class="desc_text" style="width:20em;" id="notes_editor">This is<br/>a test note<br/>over multiple lines<br/></textarea>';

Will this wo开发者_JS百科rk? How would I do it?

Thanks


as of nl2br() didn't help second proposal is append \ to all line breaks. in some kind of manner:

preg_replace('!([\r\n]+)!', '\\\$1', $text);

to be clear, the sample:

var baz = 'foo
bar';

now become:

var baz = 'foo\
bar';


Use json_encode() to output a value for javascript.

var editnotes = <?php echo json_encode($str); ?>;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜