问题
I've asked this question before but I didn't seem to get the right answer. I've got a problem with new lines in text. Javascript and jQuery don't like things like this:
alert('text
text);
When I pull information from a database table that has a break line in it, JS and jQuery can't parse it correctly. I've been told to use n2lbr(), but that doesn't work when someone uses 'shift+enter' or 'enter' when typing text into a message (which is where I get this problem). I still end up with separate lines when using it. It seems to correctly apply the BR tag after the line break, but it still leaves the break there.
Can anyone provide some help here? I get the message data with jQuery and send it off to PHP file to storage, so I'd like to fix the problem there.
This wouldn't be a problem normally, but I want to pull all of a users messages when they first load up their inbox and then display it to them via jQuery when they select a certain message.
回答1:
You could use a regexp to replace newlines with spaces:
alert('<?php preg_replace("/[\n\r\f]+/m","<br />", $text); ?>');
The m
modifier will match across newlines, which in this case I think is important.
edit: sorry, didn't realise you actually wanted <br />
elements, not spaces. updated answer accordingly.
edit2: like @LainIwakura, I made a mistake in my regexp, partly due to the previous edit. my new regexp only replaces CR/NL/LF characters, not any whitespace character (\s
). note there are a bunch of unicode linebreak characters that i haven't acknowledged... if you need to deal with these, you might want to read up on the regexp syntax for unicode
回答2:
Edit: Okay after much tripping over myself I believe you want this:
$str = preg_replace('/\n+/', '<br />', $str);
And with that I'm going to bed...too late to be answering questions.
回答3:
I usually use json_encode() to format string for use in JavaScript, as it does everything that's necessary for making JS-valid value.
来源:https://stackoverflow.com/questions/6648474/removing-break-lines