Formatting text received via api - php

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

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

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

remove HTML from displaying in PHP

I have this text : http://pastebin.com/2Zgbs7hi
And i want to be able to remove the HTML code from it and just display the plain text but i want to keep at least one line break where there are currently a few line breaks
i have tried:
$ticket["summary"] = 'pastebin example';
$TicketSummaryDisplay = nl2br($ticket["summary"]);
$TicketSummaryDisplay = stripslashes($TicketSummaryDisplay);
$TicketSummaryDisplay = trim(strip_tags($TicketSummaryDisplay));
$TicketSummaryDisplay = preg_replace('/\n\s+$/m', '', $TicketSummaryDisplay);
echo $TicketSummaryDisplay;
that is displaying as plain text, but it shows it all as one big block of text with no line breaks at all
Maybe this will earn you some time.
<?php
libxml_use_internal_errors(true); //crazy o tags
$html = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$dom = new DOMDocument;
$dom->loadHTML($html);
$result='';
foreach ($dom->getElementsByTagName('p') as $node) {
if (strstr($node->nodeValue, 'Legal Disclaimer:')){
break;
}
$result .= $node->nodeValue;
}
echo $result;
This example should successfully store text from html into an array of strings.
After stripping all the tags, you can use preg_split with \R special character ( matches any newline sequence ) to convert string into array. That array will now have several blank values, and there will be also some amount of html non-breaking space entities, so we will check the array for empty values with array_filter() function ( it will remove all items that do not satisfy the filter conditions, in our case, an empty value ). Here are a problem with entity, because and space characters are not the same, they have different ASCII code, so trim() function will not remove spaces. Here are two possible solutions, the first uncommented part will only replace &nbsp and check for white space characters, while the second commented one will decode all html entities and also check for spaces.
PHP:
$text = file_get_contents( 'http://pastebin.com/raw.php?i=2Zgbs7hi' );
$text = strip_tags( $text );
$array = array_filter(
preg_split( '/\R/', $text ),
function( &$item ) {
$item = str_replace( ' ', ' ', $item );
return trim( $item );
// $item = html_entity_decode( $item );
// return trim( str_replace( "\xC2\xA0", ' ', $item ) );
}
);
foreach( $array as $value ) {
echo $value . '<br />';
}
Array output:
Array
(
[8] => Hi,
[11] => Ashley has explained that I need to ask for another line and broadband for the wifi to work, please can you arrange this.
[13] => Regards
[23] => Legal Disclaimer:
[24] => This email and its attachments are confidential. If you received it by mistake, please don’t share it. Let us know and then delete it. Its content does not necessarily represent the views of The Dragon Enterprise
[25] => Centre and we cannot guarantee the information it contains is complete. All emails are monitored and may be seen by another member of The Dragon Enterprise Centre's staff for internal use
)
Now you should have clear array with only items with value in it. By the way, newlines in HTML are expressed through <br />, not through \n, your example as response in a web browser still has them, but they are only visible in page source code. I hope I did not missed the point of the question.
try this get text output with line brakes
<?php
$ticket["summary"] = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$TicketSummaryDisplay = nl2br($ticket["summary"]);
echo strip_tags($TicketSummaryDisplay,'<br>');
?>
You are asking on how to add line-breaks to your "one big block of text with no line breaks at all".
Short answer
After you stripped the HTML tags, apply wordwrap with a desired text-block length
$text = wordwrap($text, 90, "<br />\n");
I really wonder, why nobody suggested that function before.
there is also chunk_split around, which doesn't take words into account and just splits after a certain number of chars. breaking words - but that's not what you want, i guess.
PHP
<?php
$text = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
/**
* Returns string without html tags, also
* removes takes control chars, spaces and " " into account.
*/
function dropHtmlTags($string) {
// remove html tags
//$string = preg_replace ('/<[^>]*>/', ' ', $string);
$string = strip_tags($string);
// control characters and "&nbsp"
$string = str_replace("\r", '', $string); // remove
$string = str_replace("\n", ' ', $string); // replace with space
$string = str_replace("\t", ' ', $string); // replace with space
$string = str_replace(" ", ' ', $string);
// remove multiple spaces
$string = preg_replace('/ {2,}/', ' ', $string);
$string = trim($string);
return $string;
}
$text = dropHtmlTags($text);
// The Answer: insert line breaks after 95 chars,
// to get rid of the "one big block of text with no line breaks at all"
$text = wordwrap($text, 95, "<br />\n");
// if you want to insert line-breaks before the legal disclaimer,
// uncomment the next line
//$text = str_replace("Regards Legal Disclaimer", "<br /><br />Regards Legal Disclaimer", $text);
echo $text;
?>
Result
first section shows your text block
second section shows the text with wordwrap applied (code from above)
Hello it can be done as follows:
$abc= file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$abc = strip_tags("\n", $abc);
echo $abc;
Please, let me know whether it works
you may use
<?php
$a= file_get_contents('a.txt');
echo nl2br(htmlspecialchars($a));
?>
<?php
$handle = #fopen("pastebin.html", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
output is
Hi,
Ashley has explained that I need to ask for another line and broadband for the wifi to work, please can you arrange this.
Regards
Legal Disclaimer:
This email and its attachments are confidential. If you received it by mistake, please don’t share it. Let us know and then delete it. Its content does not necessarily represent the views of The Dragon Enterprise
Centre and we cannot guarantee the information it contains is complete. All emails are monitored and may be seen by another member of The Dragon Enterprise Centre's staff for internal use
You can probably write additional code to convert to spaces etc.
I'm not sure I did understand everything correctly but this seems to be your expected result:
$txt = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
var_dump(preg_replace("/(\&nbsp\;(\s{1,})?)+/", "\n", trim(strip_tags(preg_replace("/(\s){1,}/", " ", $txt)))));
//more readable
$txt = preg_replace("/(\s){1,}/", " ", $txt);
$txt = trim(strip_tags($txt));
$txt = preg_replace("/(\&nbsp\;(\s{1,})?)+/", "\n", $txt);
The strip_tags() function strips HTML and PHP tags from a string, if that is what you are trying to accomplish.
Examples from the docs:
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
The above example will output:
Test paragraph. Other text
<p>Test paragraph.</p> Other text

echo characters only in one line with explode function php

here is what i want to do
i am working with php explode function trying to limit characters it prints after defined condition
{
$result=http://php.net
new line characters i don't want to print
$links =explode("://",$result);
$nows=$links[1];
echo $nows;
}
as you can see the above code will print
php.net
new line characters i don't want to print
but instead i want to stop printing after
php.net
You can replace newline characters with nothing:
$nows = str_replace("\n", "", $links[1]);
$nows = str_replace("\r", "", $nows);
echo $nows;
If you want only what is printed on the first line, try this:
$result = "php.net
and some other text";
$nows = reset(explode("\n", str_replace("\r\n", "\n", $result)));
If the part you're looking after will always be in the first line:
$result="http://php.net
new line characters i don't want to print";
$links = explode("\n",$result);
/*
$links[0] ->http://php.net
$links[1] ->new line characters i don't want to print
*/
$links =explode("://",$links[0]);
$nows=$links[1];
echo $nows;
/*
php.net
*/
Anyway , Consider giving more details about your case in order to offer a better way.
For instance , maybe regex?
Try
$nows = trim( $links[1] );
TRIM() will remove newlines among other things
Manual page
EDIT:
Well now we have the actual situation which you say is :-
$result=http://php.net</br>nameserver:ns1</br>nameserver:ns2.
Try
$t = explode( '</br>', $result );
$t1 = explode ( '://', $t[0] );
echo $t1[1];
Just as a note, if it is you that is creating this string somewhere else </br> is not a valid html tag, it should be <br> or if you are using XHTML it should be <br />.

Get each line from textarea

<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>
$text = value from this textarea;
How to:
1) Get each line from this textarea ($text) and work with them using foreach()?
2) Add <br /> to the end of each line, except the last one?
3) Throw each line to an array.
Important - text inside textarea can be multilanguage.
Have tried to use:
$text = str_replace('\n', '<br />', $text);
But it doesn't work.
Thanks.
You will want to look into the nl2br() function along with the trim().
The nl2br() will insert <br /> before the newline character (\n) and the trim() will remove any ending \n or whitespace characters.
$text = trim($_POST['textareaname']); // remove the last \n or whitespace character
$text = nl2br($text); // insert <br /> before \n
That should do what you want.
UPDATE
The reason the following code will not work is because in order for \n to be recognized, it needs to be inside double quotes since double quotes parse data inside of them, where as single quotes takes it literally, IE "\n"
$text = str_replace('\n', '<br />', $text);
To fix it, it would be:
$text = str_replace("\n", '<br />', $text);
But it is still better to use the builtin nl2br() function, PHP provides.
EDIT
Sorry, I figured the first question was so you could add the linebreaks in, indeed this will change the answer quite a bit, as anytype of explode() will remove the line breaks, but here it is:
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
}
If you do it this way, you will need to append the <br /> onto the end of the line before the processing is done on your own, as the explode() function will remove the \n characters.
Added the array_filter() to trim() off any extra \r characters that may have been lingering.
You could use PHP constant:
$array = explode(PHP_EOL, $text);
additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution
Old tread...? Well, someone may bump into this...
Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you
Rather than using:
$values = explode("\n", $value_string);
Use a safer method like:
$values = preg_split('/[\n\r]+/', $value_string);
Use PHP DOM to parse and add <br/> in it. Like this:
$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');
//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;
//split it by newlines
$lines = explode("\n", $lines);
//add <br/> at end of each line
foreach($lines as $line)
$output .= $line . "<br/>";
//remove last <br/>
$output = rtrim($output, "<br/>");
//display it
var_dump($output);
This outputs:
string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)
It works for me:
if (isset($_POST['MyTextAreaName'])){
$array=explode( "\r\n", $_POST['MyTextAreaName'] );
now, my $array will have all the lines I need
for ($i = 0; $i <= count($array); $i++)
{
echo (trim($array[$i]) . "<br/>");
}
(make sure to close the if block with another curly brace)
}
$array = explode("\n", $text);
for($i=0; $i < count($array); $i++)
{
echo $line;
if($i < count($array)-1)
{
echo '<br />';
}
}
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
For a <br> on each line, use
<textarea wrap="physical"></textarea>
You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.
Hope this helps

Categories