2

I'm having text like this:

some text \r\n \r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n some text \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n some text \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n

I need to replace each block of multiple \r\n with just one <br/>

I tried to use str_replace('\\r\\n','<br/>',$text); but I ended up with too many <br/>

I need the final output to be like this:

some text <br/> some text <br/> some text <br/>

2 Answers 2

6

Use a regex with a non-capturing group and quantifiers:

$result = preg_replace('/(?:\r\n *)+/', '<br />', $subject);

Explanation:

(?:   # Start a group which matches:
 \r\n # one newline combination
 [ ]* # followed by zero or more spaces
)+    # Repeat the entire group once or more, as many times as possible
Sign up to request clarification or add additional context in comments.

Comments

2

Use regular expressions:

$output = preg_replace(',(\r\n)+,', '<br />', $input);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.