Removing backslash with str_replace - php

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

Related

Remove empty space and plus sign from the beginning of a string

I have a string that begins with an empty space and a + sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first + sign using PHP. I've tried ltrim, preg_replace with several patterns and with trying to escape the + sign, I've also tried substr and str_replace. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a + sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the + sign. I'm using get_the_excerpt Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the + with substr($s, 2);, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6); and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s); which shows you exactly what you have there.
You can use explode like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
str_replace
$string = str_replace('+', '', $string);
preg_replace
$string = preg_replace('/^\+/', '', $string);
ltrim
$string = ltrim($string, '+');
substr
$string = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can use ltrim() or substr().
For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim in the above example removes all spaces and addition characters from the left hand side of the original string.

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 .

Regex to trim text between tags

I expected this to be a simple regex but I guess my head isn't screwed on this morning!
I'm taking the source code of a page and tidying it up with a bunch of other preg_replaces, so by the time we get to the regex below, the result is already a single line string with things like comments stripped out, etc.
All I'm looking to do now is trim the texts between > and < char's down to remove extra whitespace. I.e.
<p> hello world </p>
should become
<p>hello world</p>
I figured this would do the trick, but it seems to do nothing?
$data = trim(preg_replace('/>(\s*)([^\s]*?)(\s*)</', '>$2<', $data));
Cheers.
Here's a ridiculous way to do it lol:
$str = "<p> hello world </p>";
$strArr = explode(" ", $str);
$strArr = array_filter($strArr);
var_dump(implode(" ",$strArr));
Use the power of arrays to remove the white spaces lol
you can use the /e modifier in regex to use the trim() function while replacing.
$data = preg_replace('/>([^<]*)</e', '">" . trim("$1") . "<"', $data);
A regex could be:
>\s+(.*[^\s])\s+<
but don't use it, there are better ways to reach that goal (example: HTMLtidy)
You may use this snippet of code.
$x = '<p> hello world </p>';
$foo = preg_replace('/>\s+/', '>', $x); //first remove space after ">" symbol
$foo = htmlentities(preg_replace('/\s+</', '<', $foo)); //now remove space before "<" symbol
echo $foo;

Remove newline character from a string using PHP regex

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

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