Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace replacing line break

Tags:

regex

php

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?

like image 903
user1592380 Avatar asked Sep 19 '12 15:09

user1592380


People also ask

How to remove line break in PHP?

The line break can be removed from string by using str_replace() function.

What is preg_ replace in PHP?

The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content. Syntax: preg_replace( $pattern, $replacement, $subject, $limit, $count ) Parameters: This function accepts five parameters as mention above and describe below.

What is the difference between Preg_replace and Str_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

What is pregreplace?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.


1 Answers

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).

like image 54
Antti Rytsölä Avatar answered Sep 25 '22 18:09

Antti Rytsölä