Skip to content
Advertisement

How to replace new lines by regular expressions

How can I set any quantity of new lines with a regular expression?

$var = "<p>some text</p><p>another text</p><p>more text</p>";
$search = array("</p>s<p>");
$replace = array("</p><p>");
$var = str_replace($search, $replace, $var);

I need to remove every new line (n), not <br/>, between two paragraphs.

Advertisement

Answer

To begin with, str_replace() (which you referenced in your original question) is used to find a literal string and replace it. preg_replace() is used to find something that matches a regular expression and replace it.

In the following code sample I use s+ to find one or more occurrences of white space (new line, tab, space…). s is whitespace, and the + modifier means one or more of the previous thing.

<?php
  // Test string with white space and line breaks between paragraphs
$var = "<p>some text</p>    <p>another text</p>
<p>more text</p>";

  // Regex - Use ! as end holders, so that you don't have to escape the
  // forward slash in '</p>'. This regex looks for an end P then one or more (+)
  // whitespaces, then a begin P. i refers to case insensitive search.
$search = '!</p>s+<p>!i';

  // We replace the matched regex with an end P followed by a begin P w no
  // whitespace in between.
$replace = '</p><p>';

  // echo to test or use '=' to store the results in a variable. 
  // preg_replace returns a string in this case.
echo preg_replace($search, $replace, $var);
?>

Live Example

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement