Remove newline character from a string using PHP regex - php

How can I remove a new line character from a string using PHP?

$string = str_replace(PHP_EOL, '', $string);
or
$string = str_replace(array("\n","\r"), '', $string);

$string = str_replace("\n", "", $string);
$string = str_replace("\r", "", $string);

To remove several new lines it's recommended to use a regular expression:
$my_string = trim(preg_replace('/\s\s+/', ' ', $my_string));

Better to use,
$string = str_replace(array("\n","\r\n","\r"), '', $string).
Because some line breaks remains as it is from textarea input.

Something a bit more functional (easy to use anywhere):
function strip_carriage_returns($string)
{
return str_replace(array("\n\r", "\n", "\r"), '', $string);
}

stripcslashes should suffice (removes \r\n etc.)
$str = stripcslashes($str);
Returns a string with backslashes stripped off. Recognizes C-like \n,
\r ..., octal and hexadecimal representation.

Try this out. It's working for me.
First remove n from the string (use double slash before n).
Then remove r from string like n
Code:
$string = str_replace("\\n", $string);
$string = str_replace("\\r", $string);

Let's see a performance test!
Things have changed since I last answered this question, so here's a little test I created. I compared the four most promising methods, preg_replace vs. strtr vs. str_replace, and strtr goes twice because it has a single character and an array-to-array mode.
You can run the test here:
        https://deneskellner.com/stackoverflow-examples/1991198/
Results
251.84 ticks using preg_replace("/[\r\n]+/"," ",$text);
81.04 ticks using strtr($text,["\r"=>"","\n"=>""]);
11.65 ticks using str_replace($text,["\r","\n"],["",""])
4.65 ticks using strtr($text,"\r\n"," ")
(Note that it's a realtime test and server loads may change, so you'll probably get different figures.)
The preg_replace solution is noticeably slower, but that's okay. They do a different job and PHP has no prepared regex, so it's parsing the expression every single time. It's simply not fair to expect them to win.
On the other hand, in line 2-3, str_replace and strtr are doing almost the same job and they perform quite differently. They deal with arrays, and they do exactly what we told them - remove the newlines, replacing them with nothing.
The last one is a dirty trick: it replaces characters with characters, that is, newlines with spaces. It's even faster, and it makes sense because when you get rid of line breaks, you probably don't want to concatenate the word at the end of one line with the first word of the next. So it's not exactly what the OP described, but it's clearly the fastest. With long strings and many replacements, the difference will grow because character substitutions are linear by nature.
Verdict: str_replace wins in general
And if you can afford to have spaces instead of [\r\n], use strtr with characters. It works twice as fast in the average case and probably a lot faster when there are many short lines.

Use:
function removeP($text) {
$key = 0;
$newText = "";
while ($key < strlen($text)) {
if(ord($text[$key]) == 9 or
ord($text[$key]) == 10) {
//$newText .= '<br>'; // Uncomment this if you want <br> to replace that spacial characters;
}
else {
$newText .= $text[$key];
}
// echo $k . "'" . $t[$k] . "'=" . ord($t[$k]) . "<br>";
$key++;
}
return $newText;
}
$myvar = removeP("your string");
Note: Here I am not using PHP regex, but still you can remove the newline character.
This will remove all newline characters which are not removed from by preg_replace, str_replace or trim functions

Related

Get rid of multiple white spaces in php or mysql

I have a form which takes user inputs; Recently, I have come across many user inputs with multiple white spaces.
Eg.
"My tests are working fine!"
Is there any way I can get rid of these white spaces at PHP level or MySQL level?
Clearly trim doesn't work here.
I was thinking of using Recursive function but not sure if there's an easy and fast way of doing this.
my code so far is as below:
function noWhiteSpaces($string) {
if (!empty($string)) {
$string = trim($string);
$new_str = str_replace(' ', ' ', $string);
} else {
return false;
}
return $new_str;
}
echo noWhiteSpaces("My tests are working fine here !");
If the input is actual whitespaces and you want to replace them with a single space, you could use a regular expression.
$stripped = preg_replace('/\s+/', ' ', $input);
\s means 'whitespace' character. + means one or more. So, this replaces every instance of one or more whitespace characters' in $input with a single space. See the preg_replace() docs, and a nice tutorial on regexes.
If you're not looking to replace real whitespace but rather stuff like , you could do the same, but not with \s. Use this instead:
$stripped = preg_replace('/( )+/', ' ', $input);
Note how the brackets enclose .

Removing backslash with str_replace

So I'm trying to remove a backslash (stored in database as in example - How\'s it going).
What i want to do is to remove that backslash and keep the newlines and spaces aswell.
I know that this does the trick :
str_replace('\\', '', $string);
but the issue is that I have two other expressions aswell so right now I have:
str_replace('\\r\\n', "\r\n", $string);
How and where do I put in the '\\', '' in the second example without interferring with the newlines?
I have simply tried str_replace('\\r\\n\\', "\r\n ', $string) and so on but I can't get it to work without messing up the newlines.
Anyone who can help me?
EDIT:
What I have now to output the data is:
echo nl2br(str_replace('\\r\\n', "\r\n", $string));
Which displays a string stored in the db, How\'s it going?\r\n\r\nROW 3 as:
How\'s it going?
ROW 3
In a paragraph tag.
So what I want is to keep the newlines intact. Stripslashes removes the newlines and puts the output in one row.
When storing the data I'm using this clean function:
function clean($mysqli, $var) {
$var = strip_tags($var);
$var = htmlentities($var);
$var = stripslashes($var);
return $mysqli->real_escape_string($var);
}
What could I adjust to keep the newlines and also remove the single backslash in words like It's, what's, how's etc..
EDIT: SOLVED
Just use stripslashes function
http://php.net/manual/en/function.stripslashes.php
I don't know if this is considered a good practice but what I did was:
$output = nl2br(str_replace('\\r\\n', "\r\n", $string));
echo str_replace('\\', "", $output);

regexp add space after comma but not when comma is thousands separator?

Using php regexp in a simple way, is it possible to modify a string to add a space after commas and periods that follow words but not after a comma or period that is preceded and followed by a number such as 1,000.00?
String,looks like this with an amount of 1,000.00
Needs to be changed to...
String, looks like this with an amount of 1,000.00
This should allow for multiple instances of course... Here is what I am using now but it is causing numbers to return as 1, 000. 00
$punctuation = ',.;:';
$string = preg_replace('/(['.$punctuation.'])[\s]*/', '\1 ', $string);
You could replace '/(?<!\d),|,(?!\d{3})/' with ', '.
Something like:
$str = preg_replace('/(?<!\d),|,(?!\d{3})/', ', ', $str);
I was searching for this regex.
This post really help me, and I improve solution proposed by Qtax.
Here is mine:
$ponctuations = array(','=>', ','\.'=>'. ',';'=>'; ',':'=>': ');
foreach($ponctuations as $ponctuation => $replace){
$string = preg_replace('/(?<!\d)'.$ponctuation.'(?!\s)|'.$ponctuation.'(?!(\d|\s))/', $replace, $string);
}
With this solution, "sentence like: this" will not be changed to "sentence like: this" (whith 2 blanck spaces)
That's all.
Although this is quite old, I was looking for this same question, and after understanding solutions given I have a different answer.
Instead of checking for character before the comma this regex checks the character after the comma and so it can be limited to alphabetic ones. Also this will not create a string with two spaces after a comma.
$punctuation = ',.;:';
$string = preg_replace("/([$punctuation])([a-z])/i",'\1 \2', $string);
Test script can be checked here.

An explode() function that ignores characters inside quotes?

Does somebody know a quick and easy explode() like function that can ignore splitter characters that are enclosed in a pair of arbitrary characters (e.g. quotes)?
Example:
my_explode(
"/",
"This is/a string/that should be/exploded.//But 'not/here',/and 'not/here'"
);
should result in an array with the following members:
This is
a string
that should be
exploded.
But 'not/here',
and 'not/here'
the fact that the characters are wrapped in single quotes would spare them from being splitters.
Bonus points for a solution that can deal with two wrapper characters
(not/here)
A native PHP solution would be preferred, but I don't think such a thing exists!
str_getcsv($str, '/')
There's a recipe for <5.3 on the linked page.
This is near-impossible with preg_split, because you can't tell from the middle of the string whether you're between quotes or not. However, preg_match_all can do the job.
Simple solution for a single type of quote:
function quoted_explode($subject, $delimiter = ',', $quote = '\'') {
$regex = "(?:[^$delimiter$quote]|[$quote][^$quote]*[$quote])+";
preg_match_all('/'.str_replace('/', '\\/', $regex).'/', $subject, $matches);
return $matches[0];
}
That function will have all kinds of problems if you pass it certain special characters (\^-], according to http://www.regular-expressions.info/reference.html), so you'll need to escape those. Here's a general solution that escapes special regex characters and can track multiple kinds of quotes separately:
function regex_escape($subject) {
return str_replace(array('\\', '^', '-', ']'), array('\\\\', '\\^', '\\-', '\\]'), $subject);
}
function quoted_explode($subject, $delimiters = ',', $quotes = '\'') {
$clauses[] = '[^'.regex_escape($delimiters.$quotes).']';
foreach(str_split($quotes) as $quote) {
$quote = regex_escape($quote);
$clauses[] = "[$quote][^$quote]*[$quote]";
}
$regex = '(?:'.implode('|', $clauses).')+';
preg_match_all('/'.str_replace('/', '\\/', $regex).'/', $subject, $matches);
return $matches[0];
}
(Note that I keep all of the variables between square brackets to minimize what needs escaping - outside of square brackets, there are about twice as many special characters.)
If you wanted to use ] as a quote, then you probably wanted to use [ as the corresponding quote, but I'll leave adding that functionality as an exercise for the reader. :)
Something very near with preg_split : http://fr2.php.net/manual/en/function.preg-split.php#92632
It handles multiple wrapper characters AND multiple delimiter characters.

Remove excess whitespace from within a string

I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can't find a way to remove the excess white space from between the strings.
What would be the best way to remove the inner whitespace characters?
Not sure exactly what you want but here are two situations:
If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.
If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".
Example:
$foo = preg_replace('/\s+/', ' ', $foo);
$str = str_replace(' ','',$str);
Or, replace with underscore, & nbsp; etc etc.
none of other examples worked for me, so I've used this one:
trim(preg_replace('/[\t\n\r\s]+/', ' ', $text_to_clean_up))
this replaces all tabs, new lines, double spaces etc to simple 1 space.
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extra spaces, as well as leading and trailing spaces.
If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . "
And you expect the answer to be
"this string have lots of space", you can use the following solution:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.
In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.
function secureRip(string $str): string { /* Rips all whitespace securely. */
$arr = str_split($str, 1);
$retStr = '';
foreach ($arr as $char) {
$retStr .= trim($char);
}
return $retStr;
}
$str = preg_replace('/[\s]+/', ' ', $str);
You can use:
$str = trim(str_replace(" ", " ", $str));
This removes extra whitespaces from both sides of string and converts two spaces to one within the string. Note that this won't convert three or more spaces in a row to one!
Another way I can suggest is using implode and explode that is safer but totally not optimum!
$str = implode(" ", array_filter(explode(" ", $str)));
My suggestion is using a native for loop or using regex to do this kind of job.
To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this
? productID =26%20via%20#LFS
Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.
$productID=preg_replace('/[\s]+.*/','',$productID);
I look for a space in the URL and then remove everything after it.
I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str))).
Laravel 9.7 intruduced the new Str::squish() method to remove extraneous whitespaces including extraneous white space between words: https://laravel.com/docs/9.x/helpers#method-str-squish
$str = "I am a PHP Developer";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
if (isset($str_arr[$i + 1]) && $str_arr[$i] == ' ' && $str_arr[$i] == $str_arr[$i + 1]) {
unset($str_arr[$i]);
}
else {
continue;
}
}
echo implode("", $str_arr);

Categories