str_replace multiple empty lines with 1 single line - php

I would like to replace multiple empty lines with one single line in php. currently I am replacing = with whitespace.
$message = str_replace('=', ' ', $message);
any suggestion on how to remove multiple {could even be 5 empty lines} with just one?
Output
Received On Thu, 29 May 2014 - 01:50 AM / user#test.com
= test
=

$message = 'Received On Thu, 29 May 2014 - 01:50 AM / user#test.com
= test
=';
echo preg_replace('/\n(\s*\n){2,}/', "\n\n", $message); // Quotes are important here.
OR
echo preg_replace('/\n(\s*\n){2,}/', "<br><br>", $message); //worked in browser

here is variant which replaces multiple new line symbols with any new line/space/tabs symbols after with single new line symbol:
$message = preg_replace('/[\r\n][\r\n\t ]*/', "\n", $message);
update: if you want to transform multi-line text in single line of text, you can use:
$message = preg_replace('/[\r\n][\r\n\t ]*/', " ", $message);

Related

php formatting new lines and spacing

This is a little complicated to explain but I'll try my hardest, I'm trying to create a tool to edit channel descriptions for TeamSpeak 3, to do this you use a feature called channeledit.
example usage: channeledit channel_description=My\sDescription
Presumably \s = space \n = newline, is there any possible way from using a textarea to php script to have it output the line as:
My\sDescription\nWelcome\sto\smy\sServer
Rather than appearing as:
My Description
Welcome to my Server
If there is spacing or line breaks, this kills the command and stops it working. Can anyone give me a bit of help here?
Code for this is:
$name = "Test
Test
Test test test";
$ts3_VirtualServer->execute("channeledit cid=" . $current_cid . " channel_description=" . $name);
$name = "Test Test
Test test test";
(string)$newname = str_replace(' ', '\\s', $name);
$newname = urldecode(str_replace('%0A', "\\n", urlencode($newname)));
You need to escape (\) the backslash (\). %0A 's are easier to find.
My output:
Test\sTest\nTest\stest\stest
$name=STR_replace(" ","/s",$name)
$name= str_replace("\n", '\n', $name);
If you want to replace spaces and carriage returns with literal \n and \s. I would do the following:
$name = urldecode(str_replace("%0D%0A","\\n",str_replace("+","\\s",urlencode($name))));

Convert enter key to space in php?

I have this string :
$msg = 'A:1509 B:54
1.NS:22
2.TR:56
3.MD:547
4.STS:22
5.SR:15 ';
it would show normal horizontal string. but the variable separated by enter key....
how to convert the enter key to space. thanks
You need to replace any \r or \n characters. You can do that like this:
$msg = str_replace(array("\r", "\n", " "), ' ', $msg);
This replaces anything in the array("\r", "\n", " ") with a space and assigns the new value back to $msg. (The last entry is to address the point from the comments that \r\n would result in two spaces.)
You are trying to get all of the contents onto one line? You could try replacing the new line characters
$msg = str_replace(array("\n", "\r"), ' ', $msg);
This is how to handle it:
$msg = str_replace(chr(0x0D), ' ', $msg);
$msg = str_replace(chr(0x0A), ' ', $msg);

PHP: Telegram Bot: Insert line break to text message

"\n" and "\r\n", tested in text message sent by telegram bot, to create line break. Instead of showing line break, underline _ will appear after using them.
How I could printing line feed in telegram message sent by bot?
CODE
$txt = 'با تشکر از عضویت شما، هر روز حدود ساعت 10 شب یک ویدئوی جالب برای شما ارسال خواهد شد.';
$txt .= " \n ";
$txt .= 'Thanks for joining, Every day at almost 18:30 GMT an intersting video will be sent';
Message Demo
Any help will be appreciated.
There is a better way! The problem is because of URL encodings...
You can use normal PHP text using \n but by passing it to urlencode method, as follows:
$txt = urlencode("here is my text.\n and this is a new line \n another new line");
It works for me!
1) If you develop your code in Windows/Linux OS, you can simply use enter in text:
$text = 'test 123
another text';
Thats all!
2) If your code run on Windows/Linux server, you can use PHP_EOL constant instead of \n:
$text = 'text 123 '.PHP_EOL.'yet another text';
3) And if you search for an OS independent soloution, you can use %0A or chr(10) for this purpose:
$text = 'text 123 '.chr(10).'yet another text';
For future visitor just I quote #Dagon answer in comments:
Using %0A will make line feed in telegram messages
You can use %0A instead of \n.
After reading and trying all of these answers, I just wanted to post my own solution. I have an application in Laravel 5.8 that sends the reservation both by e-mail and a Telegram message.
$telegramMessage =
"<strong>Reservation Request</strong>\n".
'<strong>Name:</strong> ' . $reservation->reserv_name . "\n".
'<strong>E-mail:</strong> ' . $reservation->email . "\n".
'<strong>Phone:</strong> ' . $reservation->phone . "\n".
'<strong>Reservation Date/Time:</strong> ' . $reservation->reserv_date_time->format('d-m-Y H:i') . "\n".
'<strong>Number of people:</strong> ' . $reservation->number_of_people . "\n".
'<strong>Message:</strong> ' . $reservation->reserv_message . "\n";
Telegram::sendMessage([
'chat_id' => env('TELEGRAM_CHAT_ID', ''),
'parse_mode' => 'HTML',
'text' => $telegramMessage,
]);
More or less I have used all the html tags that Telegram API allows. You should pay attention \n must be in double quotes.
it may be not show result as you wants in Unicode languages like Persian!
you can prepare your text and use this:
$txt = implode("\n", explode('\n', $txt));
To avoid coding and encoding issues, I used this simple solution in my code:
First, I send my text message in HTML format by setting the parse_mode=HTML argument in the "sendMessage" URL.
Then, I insert the following code for each line break:
<pre>\n</pre>
ie.
... sendMessage?parse_mode=HTML&text="... paragraph1<pre>\n</pre>paragraph2 ..."
Of course the text variable was curl escaped before appended to the URL:
$text = curl_escape($handle, $text);
for me this solution works:
use double quotation mark
$message='Hi'
$message=$message."\n";
$message=$message.'Guys'
All these answers are at the same time "right" and "wrong". In fact in depend a lot of the input you have. For example if you have a text area for input and then send the content to Telegram, if the user write in the text area and press return, the text in Telegram will be
hello\neverybody
and not
hello
everybody
Performing URL encode will change nothing. After struggling a lot I discover a conflict with the fact sending the text area data from a page to another page escape some data.
The way I solve that is to remplace the escaped \n by a non-escaped one.
So:
$my_msg = str_replace("\\n","\n",$my_msg);
It works on Mac, PC and so on with text from text area.
I solved the problem in this way :
$txt = 'aaaaaaaaa\nnew line1 \nnewline2';
$parameters = array('chat_id' => $chatId, "text" => $txt);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
try here : https://telegram-bot-sdk.readme.io/docs/sendmessage
you should use urlencode to solve this problem:
$text ="sth sth
sth sth";
$text = urlencode($text);
try something like this, its work for me, and you need to add parameter parse_mode.
$text = "exampletest \n example"
or someting like this:
$text1 = 'example';
$text2 = 'next';
$data = $text1 . "\n" . $text2;
https://core.telegram.org/bots/api#formatting-options
It it easy just copy break line from anywhare to pass in code.
enter image description here
ez way😊
$txt = "Thanks for joining, Every day at </br> almost 18:30 GMT an intersting video will be sent";
or
$txt = "Thanks for joining, Every day \r\n at almost 18:30 GMT an intersting video will be sent";

how to print special characters which are a string in variable with php?

I'm making this chat server, but it doesn't work quite well. When you send a piece of text, it first gets encoded by the function base64_encode() and then gets sent to a MySQL database.
Then the receiver gets the text from that same MySQL database, which is of course first decoded by the function base64_decode().
The only problem is with the special characters like \n \' and \t: when I get the data from the database and print it between two textarea tags, I see \n as a string, and not as actual line breaks.
In short, I need to fix this problem:
$String = 'Line 1 \n Line 2';
print '<textarea>' . $String . '</textarea>';
//The result I want
//<textarea> Line 1
//Line 2 </textarea>
The function nl2br doesn't work, because tags inside a textarea tag won't work, and also because there other characters like apostrophes.
Could anybody help me?
Thanks!
You need to enclose your string into double quotes, for special characters to be evaluated.
$String = "Line 1 \n Line 2";
print '<textarea>' . $String . '</textarea>';
If you change this:
$String = 'Line 1 \n Line 2';
print '<textarea>' . $String . '</textarea>';
to this:
$String = "Line 1 \n Line 2"; // double quote
print '<textarea>' . $String . '</textarea>';
... you will get the output you want.
This one is also works same as using " ... ", however maybe helps in your case:
$string = <<<EOT
Line 1 \n Line 2
EOT;
echo '<textarea>' . $string . '</textarea>';
As the others said, your problem is Single-Quotes.

Formatting text received via api

I get text via api and sometimes the text can be like so:
hello
world!
How are you?
But I do need the text to be like this:
hello world! How are you?
How to do that?
you can replace the newlines in the text by doing:
$newmsg = str_replace("\n",' ',$yourmsg);
Here is the link to the php function documentation:
http://php.net/manual/en/function.str-replace.php
EDIT: I added a space in the code so it does "hello world..." instead of "helloworld"
Use
$str=" test
hello
world" ;
str_replace ( "\n"," " , $str
) ;
If you want number of replaced count pass the fourth argument
str_replace ( "\n"," " , $str , $count ) ;
$str=<<<EOF
hello
world!
How are you?
EOF;
$s = explode("\n",$str);
print_r(implode(" ",$s));
Here is a really ridiculous solution that I would probably use (bear in mind, ocdcoder's answer works just fine), to make sure I accounted for all possible line endings:
$line_ends = array("\r\n", "\r", "\n"); //notice the order is important.
$new_msg = str_replace($line_ends, " ", $orig_msg);
This way, if there are double line ends, it gets rid of them, but if not, it goes back and checks for single line endings.
But if you want to get more complicated, you could replace your possible carriage-returns with line-ends:
$msg_newline_fix = str_replace("\r", "\n", $orig_message);
$msg_double_newline_fix = str_replace("\n\n", "\n", $msg_newline_fix);
$newmsg = str_replace("\n", " ", $msg_double_newline_fix);
But again, I'm a bit wacky like that. Another crazy solution might be:
$msg_newline_fix = str_replace("\r", "\n", $orig_message);
$msg_array_lines = explode("\n", $msg_newline_fix);
foreach($msg_array_lines as $msg_line){
$clean_line = rtrim($msg_line);
if($clean_line !== '') {
$msg_clean_array[] = $clean_line;
}
}
$new_msg = implode(" ", $msg_clean_array);
But if you know your line endings will be new lines (\n) and not carriage returns (\r) then you are probably safe with a simple one line str_replace.
Finally, you might actually want to preserve line endings when it indicates a new paragraph, something like:
Hello
World!
This is a
new paragraph.
In which case, I would suggest normalizing the line-endings first (making it consistently the same thing so we aren't guessing) and then replacing those empty lines with some kind of safe token you can go back and replace with your new line. Something like:
$msg_carriage_fix = str_replace("\r", "\n\n", $orig_message);
$msg_double_carriage_fix = str_replace("\n\n\n", "\n\n", $msg_newline_fix);
Now we are at the point where we know each line, including empty lines, have only one \n at the end. By replacing the potential \r with two \n, and then replacing only three \n in a row with two \n we avoid the risk of removing any line endings if there were no carriage-return \rs in the first place. Then we can finally do:
$msg_hold_true_linebreaks = str_replace("\n\n", "%line-break%", $msg_double_carriage_fix);
$msg_strip_new_lines = str_replace("\n"," ",$msg_hold_true_linebreaks);
and last but not least:
$new_msg = str_replace("%line-break%","\n",$msg_strip_new_lines);
But,that is only if you really want to keep those true line-breaks and if you want to be extra sure you are ready for carriage-returns, line-ends, and the dreaded \r\n.
I would show yet another version that may shorter and involves using implode and explode, but I'm sure that's enough for now.
edit
Here is a slightly simpler version of that last suggestion, which tries to account for both line endings and intentional line breaks:
$msg_rn_fix = str_replace("\r\n", "\n", $orig_msg);
$msg_r_fix = str_replace("\r", "\n", $msg_rn_fix);
We now know each line ends with a single \n, including empty lines...
$msg_array = explode("\n", $msg_r_fix);
Normal lines each get an array value, but we also know that if the array value is nothing, that it was an intentional hard return...
foreach($msg_array as $msg_line) {
$clean_msg_lines[] = ($msg_line == '') ? "\n" : $msg_line;
}
then we put it all back together:
$new_msg = implode(" ", $clean_msg_lines);
The only flaw is that there will be an extra space before and after each line end. This is easily fixed:
$new_msg = str_replace(" \n ", "\n", $new_msg);
I like this last solution so much, I'm going to copy it below without commentary.
My favorite version
$msg_rn_fix = str_replace("\r\n", "\n", $orig_msg);
$msg_r_fix = str_replace("\r", "\n", $msg_rn_fix);
$msg_array = explode("\n", $msg_r_fix);
foreach($msg_array as $msg_line) {
$clean_msg_lines[] = ($msg_line == '') ? "\n" : $msg_line;
}
$new_msg = implode(" ", $clean_msg_lines);
$new_msg = str_replace(" \n ", "\n", $new_msg);

Categories