Phillip
Phillip

Reputation: 1570

Character Replacement: Break-Lines

I have a few areas in an application of mine that I have <textarea> tags so users can enter messages to one another. A problem with some messages had been plaguing me for a while, but I could never figure out what the problem was. I would open up all the messages at once and save them in hidden tags. When the user 'opened' the message, the data from the tag would be gathered and shown in a lightbox for the user. For some reason, it wouldn't open some of those messages.

One of my users noticed that if you used a line-break (using 'shift+enter') in the message, it would break the Javascript when it tried to retrieve the message. Since this is only a problem when trying to read the message, I should be able to replace it when the message is sent in the first place.

How can I detect a line-break and replace it when it is submitted?

str_replace(???,"/n",$string)

Upvotes: 0

Views: 1195

Answers (2)

bob-the-destroyer
bob-the-destroyer

Reputation: 3154

As you've discovered, javascript can't handle a line break mid-string. In other words, the following output will cause a js error...

<body onload="alert('te
st');">

You could add a backslash at the end of the broken line to fix this error...

<body onload="alert('te \
st');">

As user765476 said, you could use PHP's nl2br function on the text. But to add, it is usually best to do so only while you're actually building the html output. One reason being is if you ever allow users to edit text they've already submitted, they will see <br>'s everywhere in the textbox and you'll have to devise yet another script to replace those <br>'s.

If you truly want to forbid users from submitting line breaks (and any possible carriage returns) at all though, then use something like this basic PHP code to replace them with a single space...

str_replace(array("\r\n", "\r", "\n"), ' ', $message);

Note: order of search strings is important. First pass replaces all "\r\n"'s, second pass replaces any remaining "\r"'s, third pass replaces any remaining "\n"'s (Edit: I forgot "\r" is recognized in IE javascript, just not in certain other browsers).

Upvotes: 2

questioner
questioner

Reputation: 1182

Maybe this function is what you're looking for? It converts newlines to <br/> tags.

Upvotes: 0

Related Questions