Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular expressions - search and replace question 2

Status
Not open for further replies.

Dweezel

Technical User
Feb 12, 2004
428
0
0
GB
I need to parse a string and replace newline characters (either '\n' or'\r') with <p> tags.

Is preg_replace() the best function to use for this?

If there are two or more newline tags together, they must only produce one <p> tag. So if the string contained '\n\n\n' or '\r\r\r' or '\n\r', I'd need to replace it with a single <p>.

Could anyone help me out with the syntax please?

 
That regular expression is actually easier than you might think. Its English translation would be, "Any number of newlines or carriage returns in a row".

This script:
Code:
<?php

$a = array ("\r", "\n", "\r\n", "\r\r", "\n\n", "\r\n\r\n", "\r\r\n", "a\ra", "a\r\na", "\ra\r", "\r\na\r\n");

$a = preg_replace ("/([\r\n])+/", '<p>', $a);

print_r ($a);
?>

outputs:

[tt]Array
(
[0] => <p>
[1] => <p>
[2] => <p>
[3] => <p>
[4] => <p>
[5] => <p>
[6] => <p>
[7] => a<p>a
[8] => a<p>a
[9] => <p>a<p>
[10] => <p>a<p>
)[/tt]


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
I think preg_replace() is fine. Here is a great reference (and website) of regular expressions:
A quick solution (dont know if it works):

Code:
$pattern = "/\n{1,}|\r{1,}(\r\n){1,}/";
$replacement = "<p>";
echo preg_replace($pattern, $replacement, $yourStringHere);
 
Thanks a lot Sleipnir, that's exactly what I needed.

And thanks for the link Rekcor. I'll have a good look through that at the weekend.

Cheers.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top