user1592380
user1592380

Reputation: 36367

PHP preg_replace replacing line break

When renumbering an array using

$arr=array_values($arr); // Renumber array

I realized that a line break is being introduced into one of the array strings, which I don't want.

My string is going from:

Property Type

to Property

Type

In any case I am using:

$newelement = preg_replace("/[^A-Za-z0-9\s\s+]/", " ", $element);

already to remove unwanted characters prior to database insertion, so I tried to change it to:

 $newelement = preg_replace("/[^A-Za-z0-9\s\s+'<br>''<br>''/n''/cr']/", " ", $element);

But there is no change, and the ?line feed/line break/carriage return is still there.

Am I doing the preg_replace call correctly?

Upvotes: 21

Views: 86579

Answers (5)

mickmackusa
mickmackusa

Reputation: 48100

Most simply, call preg_replace() on your flat array of values and use \v+ to target each occurrence each occurrence of one or more vertical whitespaces. (Demo)

$arr = [
    'Property Type',
    'Property

Type',
    'new
    
    
    
    
lines

again'
];

var_export(
    preg_replace('/\v+/', ' ', $arr)
);

Output:

array (
  0 => 'Property Type',
  1 => 'Property Type',
  2 => 'new lines again',
)

Upvotes: 0

Dave Strickler
Dave Strickler

Reputation: 161

It's a hack, but you can do something like this:

    $email_body_string  = preg_replace("/\=\r\n$/", "", $email_body_string);

The replacement says find a line that ends with an equals sign and has the standard carriage return and line feed characters afterwards. Replace those characters with nothing ("") and the equals sign will disappear. The line below it will be pulled up to join the first line.

Now, this implies that you will never have a line that ends with an equals sign, which is a risk. If you want to do it one better, check the line length where the wrap (with the equals sign) appears. It's usually about 73 characters in from the beginning of the line. Then you could say:

    if (strlen(equals sign) == 73)
       $email_body_string  = preg_replace("/\=\r\n$/", "", $email_body_string);

Upvotes: 1

tashi
tashi

Reputation: 249

This thing worked for me.

preg_replace("/\r\n\r\n|\r\r|\n\n/", "<br />", $element);

Upvotes: 4

Mahdi
Mahdi

Reputation: 9427

This should work too:

// char(32) is whitespace
// For CR
$element = strtr($element, chr(13), chr(32));

// For LF
$element = strtr($element, chr(10), chr(32));

Upvotes: 6

Antti Ryts&#246;l&#228;
Antti Ryts&#246;l&#228;

Reputation: 1553

That preg looks a bit complicated. And then you have ^ in the beginning as not A-Z... or linefeed. So you don't want to replace linefeed?

How about

$newelement = preg_replace("/[\n\r]/", "", $element);

or

$newelement = preg_replace("/[^A-Za-z ]/", "", $element);

\s also matches linefeed (\n).

Upvotes: 43

Related Questions