Remove newline character from a digit in the string using PHP regular expression

Viewed 34

How can I remove a new line character in front of every digit from a string using PHP regular expression?

Example:

$message = "
My Number is \n
0\n
7\n
8\n
9\n
Come Home\n
"

Becomes:

$message = "
My number is\n
0789\n
Come Home\n
"

This is what I have but it delete the everything

$message = trim(preg_replace('\d+\s+', '', $message),'\n');

2 Answers

You may use this php code:

$message = preg_replace('/(?<=\d)\R+(?=\d)/', '', $message);

This will match 1+ of any line breaks if it is followed and preceded by a digit.

RegEx Demo

Another option could be:

\d\K\R+(?=\d)

Explanation

  • \d Match a single digit
  • \K Forget what is matched so far
  • \R+ Match 1+ unicode newline sequences
  • (?=\d) Positive lookahead, assert a digit directly to the right

Regex demo

$message = preg_replace('/\d\K\R+(?=\d)/', '', $message);

See a PHP demo.

Related