PHP: Telegram Bot: Insert line break to text message - php

"\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";

Related

PHP str_replace <br>, \r\n into Real New Line in MySQL [duplicate]

This question already has answers here:
Converting <br /> into a new line for use in a text area
(6 answers)
Closed 5 years ago.
I have a text with <br> tags and I want to save it into MySQL database as a new line. not HTML tags.
for example :
$string = 'some text with<br>tags here.'
and I want to save it into MySQL like this :
some text with
tags here
what right str_replace for this purpose? thank you.
There is already a function in PHP that converts a new line to a br called nl2br(). However, the reverse is not true. Instead you can create your own function like this:
function br2nl($string)
{
$breaks = array("<br />","<br>","<br/>");
return str_ireplace($breaks, "\r\n", $string);
}
Then whenever you want to use it, just call it as follows:
$original_string = 'some text with<br>tags here.';
$good_string = br2nl($original_string);
There are three things worth mentioning:
It may be better to store the data in the database exactly as the user entered it and then do the conversion when you retrieve it. Of course this depends what you are doing.
Some systems such as Windows use \r\n. Some systems such as Linux and Mac use \n. Some systems such as older Mac systems user \r for new line characters. Given this and especially if you choose to use point 1. above, you might prefer to use the PHP constant PHP_EOL instead of \r\n. This will give the correct new line character no matter what system you are on.
The method I posted above will be more efficient than preg_replace. However, it does not take into account non-standard HTML such as <br /> and other variations. If you need to take into account these variations then you should use the preg_replace() function. With that said, one can overthink all the possible variations and yet still not account for them all. For example, consider <br id="mybreak"> and many other combinations of attributes and white space.
You could use str_replace, as you suggest.
$string = 'some text with<br>tags here.';
$string = str_replace('<br>', "\r\n", $string);
Although, if your <br> tags may also be closed, <br /> or <br/>, it may be worth considering using preg_replace.
$string = 'some text with<br>tags here.';
$string = preg_replace('/<br(\s+\/)?>/', "\r\n", $string);
Here try this. This will replace all <br> to \r\n.
$string = 'some text with<br>tags here.';
str_replace("<br>","\r\n",$string);
echo $string;
Output:
some text with
tags here.
You can use htmlentities— Convert all HTML characters to entities and html_entity_decode to Convert HTML entities to characters
$string = 'some text with<br>tags here'
$a = htmlentities($string);
$b = html_entity_decode($a);
echo $a; // some text with<br>tags here
echo $b; // some text with<br>tags here
Try :
mysql_real_escape_string
function safe($value){
return mysql_real_escape_string($value);
}

str_ireplace or preg_replace replaced break tag into \r\n

I have read this post that discuss about converting html break tag into a new line in php. Other people said it's work for them but something weird happened to me.
this is the code I use:
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);`
and this is the code they use :
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
both insert "\r\n" into the text , why is this happening ?
screenshot:
if there's any previous post / PHP method let me know
EDIT : adding my code that echo the textbox
<-- THIS WONT WORK -->
$username = $_SESSION['username'];
$unsafenomorsoal = $_POST['nomorsoal'];
$unsafejawaban = $_POST['jawaban'];
$nomorsoal = mysqli_real_escape_string($konek,$unsafenomorsoal);
$jawabannotcut = substr($unsafejawaban,0,50000);
$unsafejawabanfirst = nl2br($jawabannotcut);
$jawaban1 = mysqli_real_escape_string($konek,$unsafejawabanfirst);
$breaks = array("<br />","<br>","<br/>");
$jawaban = str_ireplace($breaks, PHP_EOL, $jawaban1);
$_SESSION['textvaluejawaban'] = $jawaban;
and this is what echoed :
echo "<div class=\"head-main-recent-background\" style=\"background:white;width:99%;color:black;text-align:left;height:1000px;position:relative;top:130px;margin-top:10px;\">- Jawab Soal -<br/>".$jawabanerror."<br/>Nama : ".$_SESSION['username']."<br/>
<form method=\"post\" action=\"prosesjawabsoal.php\">
<input type=\"hidden\" name=\"nomorsoal\" value=\"".$_SESSION['nomorsoal']."\"/>
Jawaban : <br/>
<textarea placeholder=\"Max 40.000 Huruf\" style=\"overflow- x:none;width:99%;height:300px;\" type=\"text\" name=\"jawaban\" maxlength=\"40000\" >".$_SESSION['textvaluejawaban']."</textarea>
<br/>Captcha <br/>
<div style=\"overflow:hidden;\" class=\"g-recaptcha\" data- sitekey=\"6LfYQicTAAAAAFstkQsUDVgQ60x_93obnKAMKIM9\"></div><br/>
<button type=\"submit\" name=\"submit\" style=\"margin-top:10px;height:auto;width:auto;\">Kirim Jawaban</button>
</form>
</div>";
Note : The snippet won't work because it's php
Sorry i used snippet due to error while posting the code !
EDIT :
tried preg_replace() method but still same result
EDIT :
change title to tell that preg_replace not work
Your problem is the mysqli_real_escape_string(). The converts the "\r\n" into a string to make it safe to input into the database. Remove it completely. Instead use htmlspecialchars when you output to screen:
echo htmlspecialchars($myUnsafeVar);
Apply these rules (as a starting point, there's always possible exceptions, but in rare cases):
use mysqli_real_escape_string when inputting strings into a database. It won't do what you expect when outputting to screen - so anything that has been mysql escaped() should not appear on screen.
use htmlspecialchars (which you don't have!) when outputting to screen.
use url_encode for adding stuff into a URL
There are also many different "escape" function (e.g. inserting into JSON, inserting into mysql, inserting into other databases). Use the right one for what you need - and don't use it for other purposes.
Check the functions for more details.
As it currently stands your code is not safe even with all those efforts - but it's really simple to fix!
try with preg_replace() function and no need of \n\r both you can do with \n or PHP_EOL only
$jawaban = preg_replace('#<br\s*?/?>#i', "\n", $jawaban1);
or
$jawaban = preg_replace('#<br\s*?/?>#i', PHP_EOL, $jawaban1);
you must knowing these before working with strings:
"\n\r" means new line.
'\n\r' doesn't mean new line.
doesn't mean new line. It's just HTML number for HTML Symbols. when you are using it, you mean just show \n\r in your browser. this is answer to your question:
both insert "\r\n" into the text , why is this happening?
so, after knowing that, you understand:
if your $jawaban1 string is
Hello <br> and welcome!
and your code is
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);
It means, $jawaban will be exactly like this:
Hello
and welcome!
without any \n\r and just your browser showing it like this:
Hello \n\r and welcome!
If you want to replace all br by \n\r just use the code in your question:
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
About preg_replace()
When you can use str_ireplace, Don't use preg_replace. str_ireplace is faster.
Don't do it if you don't need it
in your code you did this:
$unsafejawabanfirst = nl2br($jawabannotcut);
and right after that you want to replace br with \n\r. It's like do and undo. I see that you are trying to show it again inside textarea element. so don't replace \n\r with br. the solution? don't change \n\r at all and if you want save it to the db just save it with \r\r. when you need it to show outside of textarea element just use nl2br function.
There is always something that saves my day, it is actually a workaround and your question is a trigger for me to get deeper to this matter - once for all.
For now, here you go - nice & sleek workaround:
There is already nl2br() function that replaces inserts <br> tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

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

Apostrophes getting sent as \'

function send_mails($adress, $subject, $message, &$tpl)
{
// fix for correct display of newlines and spaces in the message
$textmail = ereg_replace( "\n", "\r\n", $message);
$textmail = wordwrap($textmail, 70, "\r\n");
//prepare text to show online (html)
$textshow = ereg_replace( "\r\n", "<br>", $textmail);
$sent = '-- HTML Code to show the Mail you sent --';
$tpl->assign(BODY, $sent);
$mailtext = utf8_decode($textmail);
$headers = '-- Functional Header --';
mail ($adress, $subject, $mailtext, $headers);
}
My problem now is that if the message contains apostrophes they're show like this:
We\'re too good, so you shouldn\'t judge this example text\'s content
I've tried $textmail = ereg_replace(" \' ", " ' ", $textmail); but that didn't seem to work.
I'm pretty sure there is an easy fix, but I've been looking for some time now and haven't found a solution... Probably searching for the wrong thing.
string stripslashes ( string $str ) is what you are looking for!
$str = "We\'re too good, so you shouldn't judge this example text\'s content";
$newStr = stripslashes ( $str );
echo $newStr;
Output:
We're too good, so you shouldn't judge this example text's content
EDIT
VolkerK's comment:
I think it might be useful to first determine
whether this would fight the cause or just a symptom...
Please consider, that this is kind of Hot-Fix, you should try to find out, how and where this is actually happening?
Does $message at the beginning contain these slashes? (just echo it.)
If yes, where does $message come from?
If not, go through it all the way $message-> $textmail -> $textshow … and find out, which step does it and eliminate it there!

How to add new line in php echo

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.
The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.
I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

Categories