Detect a carriage return/new line in a text area with PHP

How do I detect a carriage return/new line character in a text area in PHP?

I want to replace them with <br /> tags before storing it in the database.

Upvotes: 6

Views: 14211

Answers (7)

Mike Wells
Mike Wells

Reputation: 426

I know this is v-old but just wanted to make a note here, perhaps even for myself! The eols here need to be in double quotes, otherwise It just won't work. See below...

$eols = array(",","\n","\r","\r\n");
$text_area = str_replace($eols,'<br />',$_POST['text_area']);

Hope this helps someone not waste time like I just did for 30mins!

Upvotes: 4

Yoshi
Yoshi

Reputation: 54659

My advice: "don't do it". Just store the line breaks in the db, but render it to <br /> only when producing the output. Otherwise you'll have the problem of replacing the <br /> when you want to use that data in a different context.

For that, you can use nl2br See: http://php.net/manual/en/function.nl2br.php

Upvotes: 8

Brad
Brad

Reputation: 163612

You can use the nl2br() function. This will insert <br/> as necessary.

It is generally my preference to leave the HTML formatting out of the DB (unless it was in the source material). You never know when you may want to use the clean version for other purposes.

Upvotes: 1

Naftali
Naftali

Reputation: 146360

Try this:

$text_area = str_replace(PHP_EOL,'<br/>', $text_area);

Using str_replace

Upvotes: -1

NikiC
NikiC

Reputation: 101956

Just nl2br it ;)

PS: Don't apply the function when inserting to the database (use only SQL escaping here). Apply the function as soon as you want to output the text to HTML.

Upvotes: 4

Paolo Stefan
Paolo Stefan

Reputation: 10283

You may use nl2br(). Please note that it will convert \n and \r\n to <br />\n.

Upvotes: 1

Denis de Bernardy
Denis de Bernardy

Reputation: 78581

There's a php constant for this:

When do I use the PHP constant "PHP_EOL"?

Also look into nl2br().

Upvotes: 9

Related Questions