Saving line breaks with preg_replace - php

I have this code for saving line breaks in text area input to database:
$input = preg_replace("/(\n)+/m", '\n', $input);
On examining the input in the database, the line breaks are actually saved.
But the problem is when I want to echo it out, the line breaks do not appear
in the output, how do I preserve the line breaks in input and also echo them
out. I don't want to use <pre></pre>.

You are replacing actual sequences of newlines in the $input with the literal two character sequence \n (backslash + n) - not a newline. These need to be converted back to newlines when read from the database. Although I suspect you intend to keep these actual newlines in the database and should be using a double quoted string instead...
$input = preg_replace('/(\n)+/m', "\n", $input);
Note that I have replaced the first string delimiters with single quotes and the second string with double quotes. \n is a special sequence in a regular expression to indicate a newline (ASCII 10), but it is also a character escape in PHP to indicate the same - the two can sometimes conflict.

I think PHP has the solution:
nl2br — Inserts HTML line breaks before all newlines in a string
Edit: You may need to replace CR / LF to make it work properly.
// Convert line endings to Unix style (NL)
$input = str_replace(array("\r\n", "\r"), "\n", $input);
// Remove multiple lines
$input = preg_replace("/(\n)+/m", '\n', $input);
// Print formatted text
echo nl2br($input);

Related

How can i put space between 2 Words [duplicate]

How do i simply write out a file including real tabs inside? tab means real tab which is not the spaces. How to write the tab or what is the character for real tab?
For example here:
$chunk = "a,b,c";
file_put_contents("chunk.csv",$chunk);
What character should i use to get tabs instead of Commas (,) there?
In the output file, there should be real tabs between the seperated words.
Real Tabs means, a true wide space we get when we press the <tab> key in a text-editor.
The tab character is \t. Notice the use of " instead of '.
$chunk = "<html>\t<head>\t\t<title>\t</head>";
PHP Strings - Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret
more escape sequences for special characters:
...
\t horizontal tab (HT or 0x09 (9) in ASCII)
Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.
Use \t and enclose the string with double-quotes:
$chunk = "abc\tdef\tghi";
This should do:
$chunk = "abc\tdef\tghi";

Identifying hidden characters

How can I identify what characters are showing up as whitespace in a string?
The string is (There's actually a blank line before it, but it doesn't show up in StackOverflow's parser):
​ \n
​\n
\n
When I paste it in regex101.com to try to add a regex to eliminate this spacing/characters it pastes as:
... which explains why trim() is not seeing it as empty spaces.
How can I find out which characters are producing these bullets so I can trim them?
What I would do is parse the string and get the ASCII character
$str = str_split('your string here');
foreach($str as $char) echo ord($char);
You'll then have the ASCII code of the character. You can theoretically work backwards from there

UTF 8 String remove all invisible characters except newline

I'm using the following regex to remove all invisible characters from an UTF-8 string:
$string = preg_replace('/\p{C}+/u', '', $string);
This works fine, but how do I alter it so that it removes all invisible characters EXCEPT newlines? I tried some stuff using [^\n] etc. but it doesn't work.
Thanks for helping out!
Edit: newline character is '\n'
Use a "double negation":
$string = preg_replace('/[^\P{C}\n]+/u', '', $string);
Explanation:
\P{C} is the same as [^\p{C}].
Therefore [^\P{C}] is the same as \p{C}.
Since we now have a negated character class, we can substract other characters like \n from it.
My using a negative assertion you can a character class except what the assertion matches, so:
$res = preg_replace('/(?!\n)\p{C}/', '', $input);
(PHP's dialect of regular expressions doesn't support character class subtraction which would, otherwise, be another approach: [\p{C}-[\n]].)
Before you do it, replace newlines (I suppose you are using something like \n) with a random string like ++++++++ (any string that will not be removed by your regular expression and does not naturally occur in your string in the first place), then run your preg_replace, then replace ++++++++ with \n again.
$string=str_replace('\n','++++++++',$string); //Replace \n
$string=preg_replace('/\p{C}+/u', '', $string); //Use your regexp
$string=str_replace('++++++++','\n',$string); //Insert \n again
That should do. If you are using <br/> instead of \n simply use nl2br to preserve line breaks and replace <br/> instead of \n

escaping slashes using php

I am trying to remove the escape sequences present in between my output. I am coding using php and I have output from the function and it contains escape sequences like \r and \n. How do I escape these stuff from output so that I get a proper output. The issue is that I am trying to add this output to a csv file, so it will take \n as next line.
Single quotes inhibit escape sequences. '\r' is two characters, \ and r; "\r" is CR.
Use str_replace function:
$your_string = "here is your string"
$your_string = str_replace("\n", "", $your_string);
$your_string = str_replace("\r", "", $your_string);
You need to use stripslashes and str_replace check them out Here and Here
This post indicates that keeping the newline in the field should work, so long as:
newlines inside cells are represented as \n (str_replace("\r\n", "\n", $cell))
cells are quoted
rows are terminated with \r\n
If you're not already I'd recommend using fputcsv(), as it will take care of the quoting for you.

How can characters " \n \t \r " be replaced with '-'?

How can characters " \n \t \r " be replaced with '-' ?
echo preg_replace('/\s/','-','\n\t\n\r\n');//output '\n\t\n\r\n' instead should be'-----'
Edit: I have dynamic content in real app like:
preg_replace('/\s/','-',$_Request['content']);
can I fix it by adding "" around variable?
preg_replace('/\s/','-',"$_Request['content']");
Edit2:
How can be string converted from format 'str' to format "str"?
Thanks
Well, two things. First, the problem is single quotes in your replacement string. Meta-Characters (\n\t\r, etc) are not processed inside of single quotes.
However, don't use a regex for this. There's no need for the complexity of the regex. Use
Either use str_replace:
echo str_replace(array("\r", "\n", "\t", "\v"), '-', "\r\n\t\r\v\n\t");
Or strtr:
echo strtr("\r\n\t\r\v\n\t", "\r\n\t\v", '----');
Edit: Ahh, now I see what you're getting at. You have a string with a literal \r\n\t\r\v\n\t in it, and want to replace them out. Well, you can do that via regex:
$regex = '/(\s|\\\\[rntv]{1})/';
$string = preg_replace($regex, '-', $_GET['content']);
Basically, it matches any space character, and any literal \ followed by either r, n, t or v...
If you are looking to replace the actual whitespace characters, you need to enclose the input string in double quotes (") so PHP converts the escape sequences for you:
echo preg_replace('/\s/', '-', "\n\t\n\r\n");
Else if the escape sequences occur literally (i.e. you see \n\t\n\r\n instead of line feed, tab, line feed, carriage return, line feed), you need to replace by the following character class (and keep single quotes (') on the input string):
echo preg_replace('/\\\\[rnt]/', '-', '\n\t\n\r\n');
You ought to be passing content through $_POST instead of $_GET, I don't know how PHP handles tabs, newlines and returns in GET variables.
You are using 's instead of "s. You should change your code to:
echo preg_replace('/\s/','-',"\n\t\n\r\n");
See here: single-quoted and double-quoted.
http://www.php.net/manual/en/language.types.string.php
There's also a string method for that:
echo strtr($str, "\r\n\t\v ", "-----");
If you want to remove linebreaks but retain spaces, then remove the trailing and the fifth -.
Since you seemingly want literal \r and \n converted, you need to use a map (or even a regex) like:
echo strtr($str, array('\\r'=>"\r", '\\n'=>"\n", '\t'=>"\t", ' '=>"␣"));
// single quoted strings escaped twice for illustration
Try:
echo preg_replace('/\s/','-',"\n\t\n\r\n");
Note the double quotes on the string.
If you enclose a string with single quotes, special characters lose their special meaning:
echo preg_replace('/\s/','-',"\n\t\n\r\n");

Categories