adding white space between clean string functions - php

I've got the following code which outputs two different strings sent from a php contact form.
$email_message .= "Module: ".clean_string($modcode_1_from)."\s".clean_string($modcode_2_from)."\r\n";
is meant to display module code 1 and module code 2.
Currently looks likes this
1001\s2002
However i want it to look like:
1001 2002
So i added \s to add white space between the strings but it does not do anything for me.

use non-breaking space or you can use \t to add a tab char. And the best one is just a space:
$email_message .= "Module: " . clean_string($modcode_1_from). " ". clean_string($modcode_2_from) . "\r\n";
$email_message .= "Module: " . clean_string($modcode_1_from) . "\t" . clean_string($modcode_2_from) . "\r\n";
$email_message .= "Module: " . clean_string($modcode_1_from) . " " . clean_string($modcode_2_from) . "\r\n";

You can use this:
$email_message .= "Module: ".clean_string($modcode_1_from)." ".clean_string($modcode_2_from)."\r\n";
What I did: I removed the \s and put a space in its place.
IMPORTANT NOTE: DO NOT USE " ", it will echo/add between 1001 and 2002.
Resulting in:
1001 2002
Therefore, replace \s with an actual space using your spacebar.
Footnote (other options):
If you wish to later use your data in Excel for example, you could use a comma ,
(CSV, comma seperated value) as the seperating character or a tab for a tab-seperated value \t i.e. "\t", or a semi-colon ; i.e. "; ".
You may need/want to add a space after the comma; i.e. ", " for use as a CSV.
Example output of using a comma: 1001, 1002.

Can you try changing the \s to
' '
and see if this works for you?

Try this,
$email_message .= "Module: ".clean_string($modcode_1_from)." ".clean_string($modcode_2_from)."\r\n";

Related

Lines not delimited by CRLF sequence near line # 1

I'm having an issue getting the line folding to work the way it's specified. I'm obviously misunderstanding something about the documentation, so I was hoping I could get some help. The validator at https://icalendar.org/validator.html is saying
Lines not delimited by CRLF sequence near line # 1
Reference: RFC 5545 3.1. Content Lines
This is my function to generate the .ics files for download:
public function getCalendarFile($event) {
header("Content-Type: text/Calendar; charset=utf-8");
header("Content-Disposition: attachment; filename="ExampleFile.ics");
$icsFile = "BEGIN:VCALENDAR\r\n";
$icsFile .= "VERSION:2.0\r\n";
$icsFile .= "PRODID:Example Event" . $event->name . "\r\n";
$icsFile .= "METHOD:PUBLISH\r\n";
$icsFile .= "BEGIN:VEVENT\r\n";
$icsFile .= "UID:". $event->name . gmdate("Ymd\THis\Z", strtotime(Carbon::now())) . "\r\n";
$icsFile .= "DTSTAMP:" . gmdate("Ymd\THis\Z", strtotime(Carbon::now())) . "\r\n";
$icsFile .= "DTSTART:" . gmdate("Ymd\THis\Z", strtotime($event->begin)) . "\r\n";
$icsFile .= "DTEND:" . gmdate("Ymd\THis\Z", strtotime($event->end)) . "\r\n";
$icsFile .= "LOCATION:" . strip_tags($event->location) . "\r\n";
$icsFile .= "SUMMARY:" . $event->name . "\r\n";
$icsFile .= "DESCRIPTION:" . $this->foldCalendarDescription(strip_tags($event->description)) . "\r\n";
$icsFile .= "END:VEVENT\r\n";
$icsFile .= "END:VCALENDAR\r\n";
echo $icsFile;
}
public function foldCalendarDescription($description) {
return wordwrap($description, 75, "\r\n\t", TRUE);
}
I'm not sure if it has something to do with strip_tags possibly? The event description is stored as a wysiwyg html input. But the issue says with line # 1 and line # 1 looks fine to me.
Here's a wrapper for ICAL strings that works for me:
function format_ical_string( $s ) {
$r = wordwrap(
preg_replace(
array( '/,/', '/;/', '/[\r\n]/' ),
array( '\,', '\;', '\n' ),
$s
), 73, "\n", TRUE
);
// Indent all lines but first:
$r = preg_replace( '/\n/', "\n ", $r );
return $r;
}
As I wrote in the comment beneath kmoser's answer, people seem to be really hard pressed to get exactly 75 bytes on a line and create very convoluted code to do that. But why not just sometimes less than 75 bytes? A simple wordwrap will give you that because it just looks for whitespace to break and is not multi-byte aware. You'll possibly have a few more linebreaks in the iCal object code than strictly neccessary, but does that matter? This is why I upvoted kmoser's answer. It's a nice and simple solution.
I've tried to create an even simpler and faster version of kmoser's answer:
function format_ical_string( $str ) {
$str = str_replace(
[ "\r\n", '\\', ',', ';', "\n" ], // replacement order is important
[ "\n", '\\\\', '\,', '\;', '\n' ], $str );
return wordwrap( $str, 73, "\n ", false );
}
The replacements (just a str_replace, because nothing fancy is needed here) are:
replace CRLF's with just LF's
replace literal backslashes with escaped backslashes
escape comma's
escape semicolons
replace newlines with a literal \n (per rfc5545)
Then wordwrap with a LF + space (per rfc5545).
After this, strictly you should replace all LF's with CRLF's (rfc5545 line ending). I tend to format the entire iCal object with just LF's, and only at the very end replace all LF's with CRLF's to make the result compliant. This saves me the hassle of repeatedly inserting these Windows line endings (who uses those these days?) during the composition of my iCal objects.
It is unclear from rfc5545 if the property name itself is counted in the 75 bytes line limit, as in https://www.rfc-editor.org/rfc/rfc5545#section-3.1:
Lines of text SHOULD NOT be longer than 75 octets, excluding the line break.
But just to be sure, I feed the property name to the function, as in:
$line = format_ical_string( 'SUMMARY:Really long text here' );
IMPORTANT: my function above will fail on single words (!) that are longer than 75 bytes. I'm not sure how common that is. If you have an 18-character word completely made of 4-byte characters, you'd be at the limit. This seems very unlikely to me.

csv_output containing with field . (full stop)

I have a php script that is generating a tab delimited .txt file that works great but I need to output a field that contains a . (full stop/ period) within the $model field i.e itemname.1 it affects the formatting of the file.
$csv_output .= $model . "\t";
$csv_output .= '' . "\t";
$csv_output .= '' . "\t";
$csv_output .= '' . "\t";
$csv_output .= $totalstock . "\t";
$csv_output .= $leadtime . "\t";
$csv_output .= "\n";
$csv_handler = fopen('../outputfile.txt','w');
fwrite ($csv_handler,$csv_output);
fclose ($csv_handler);
I have tried enclosing in double quotes and various other variations but the output is inserting newlines
example output
itemname.1
20 1
any ideas how i can output the fields with the . in them without it affecting the tabs/lines.
Could you show us your code that encloses the variable in quotes please?
The not-very-well-informed solution appears to be use replace() to test if the . is indeed causing the new line, or if it's "something else". You might just be able to replace new line straight up even.
It Was a school boy error.
The issue was the data imported into db had carriage returns on each line entry, although the data appeared correct in the db and in excel the problem only manifested in the output file.
Thanks for your help guys made me go back to source and identify the issue.

How do you show double quotes in single quotes PHP

I have a PHP echo statement:
echo "stores[".$row['BarID']."] = [". $row['BarName'] . ", " . $row['Address']. ",". $row['City']. "," . $row['State']. " 0". $row['ZipCode']. "," . $row['PhoneNumber']. ",". $row['Lattitude']. ",".$row['Longitude']. "]". ";<br>";
which outputs:
stores[0] = [The Ale 'N 'Wich Pub , 246 Hamilton St ,New Brunswick,NJ 08901,732-745-9496 ,40.4964198,-74.4561079];
BUT I WOULD LIKE THE OUTPUT IN DOUBLE QUOTES SUCH AS:
stores[0]=["The Ale 'N 'Wich Pub", "246 Hamilton St, New Brunswick, NJ 08901", "732-745-9496 Specialty: Sport", "40.4964198", "-74.4561079"];
I Have looked at the PHP String Functions Manual on PHP site but still don't understand how i can implement it. Your help is appreciated.
The keyword you miss is "escaping" (see Wiki). Simplest example:
echo "\"";
would output:
"
EDIT
Basic explanation is - if you want to put double quote in double quote terminated string you MUST escape it, otherwise you got the syntax error.
Example:
echo "foo"bar";
^
+- this terminates your string at that position so remaining bar"
causes syntax error.
To avoid, you need to escape your double quote:
echo "foo\"bar";
^
+- this means the NEXT character should be processed AS IS, w/o applying
any special meaning to it, even if it normally has such. But now, it is
stripped out of its power and it is just bare double quote.
So your (it's part of the string, but you should get the point and do the rest yourself):
echo "stores[".$row['BarID']."] = [". $row['BarName'] . ", " . $row['Address'] .
should be:
echo "stores[".$row['BarID']."] = [\"". $row['BarName'] . "\", \"" . $row['Address']. "\"
and so on.

Need a little help getting contents from a text file using while loop

So I am getting the contents out of a text file using a while loop and an array and then echoing it out. It works except for one problem which is the last line:
First name: john Last name: paul Age: 44
First name: sam Last name: smith Age: 22
First name: jim Last name: bob Age: 33
First name: Last name: Age:
My question is why does it loop again if it is at the end of the file and how do I get rid of the last line?
<?php
$fileread = fopen("textfile.txt", "r");
while (!feof($fileread)){
$list = fgets($fileread);
$arrayinfo = explode(",", $list);
echo "<b>First name: </b> " . $arrayinfo[0] . " " . "<b>Last name: </b>" . $arrayinfo[1]. " " . "<b>Age: </b>" . $arrayinfo[2] . "<br>";
}
fclose($fileread);
?>
It sounds like there's a new line at the end of the file. You can check to make sure that $arrayinfo is not empty before you echo:
if(!empty($arrayinfo))
echo "<b>First name: </b> " . $arrayinfo[0] . " " . "<b>Last name: </b>" . $arrayinfo[1]. " " . "<b>Age: </b>" . $arrayinfo[2] . "<br>";
I'm not sure why it reads the loop runs again after the last line. My guess is below. Someone who knows more is welcome to correct me.
I suspect that the EOF is a character at the end of the file. The last fgets reads the line up to a "\n" or "\r" character which comes just before the EOF character. Therefore the !feof($fileread) test is still TRUE resulting in one final read where $list is likely empty.
I'm not sure what you can do about it except run a test on each line like the following:
if (empty($list)) { break; } which would come just before $arrayInfo = explode....
Edit:
If you have a comma at the end of the file (on it's own line) then the empty check will return false and you will still print an empty line. So if:
if (empty($list)) { break; }
doesn't work then try
if (strlen($list) < 2) { break; }
This will work as long as there any spaces or such that go along with a comma at the end of the line. Past that you could test the result of explode gave you 2 usable fields liek this:
if (empty($arrayInfo[0]) || empty($arrayInfo[1])) { break; }
These problems frequently revolve around stray chars in the file so make sure the file is clean to test your logic. Then if the input files aren't all clean build filters to deal with the unclean real data.

Not getting newlines in output when using PHP_EOL

I am putting together a string that I will output to a .srt file:
while ($row = mysql_fetch_array($res)) {
$srt = $srt . $row['line_number'] . PHP_EOL;
$srt = $srt . str_replace(".", ",", $row['start']) . " --> " . str_replace(".", ",", $row['end']) .PHP_EOL ;
$srt = $srt . br2nl($row['text']) . PHP_EOL;
$srt = $srt . PHP_EOL;
}
But it seems like PHP_EOL isn't working, because my output is:
100:00:02,107 --> 00:00:05,810you sure
and doesn't have any newlines. I am trying to get my output to be:
1
00:00:02,107 --> 00:00:05,810
you sure
followed by a newline.
It works when testing through localhost on my computer. Could the PHP version on my host be missing support for PHP_EOL?
The PHP manual says the PHP_EOL constant was available since PHP 4.3.10 and PHP 5.0.2
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2 - http://php.net/manual/en/reserved.constants.php
So test to see if it exists:
var_dump(PHP_EOL); // should output: string(1) " "
OR
var_dump(defined("PHP_EOL")); // should output if exists: bool(true)
and if it is not defined, just define it manually if you want
define("PHP_EOL", "\n");
OR just use echo "\n" or echo "\r\n"
The other possible reason is when you output the $srt variable in your browser your outputting and the mime type is set in HTML and so you see it as one line, but if you view the source it should be spanned accross multiple lines.
To ensure text output you could echo out a <pre> tag if you want to keep html or at the top of your php file add this line to force text output:
header('Content-Type: text/plain', true);
PHP_EOL The correct 'End Of Line' symbol for this platform.
So it works on local host because its window and gives a windows line break
You online website is probably on linux and gives a linux line-break
To get a consistent result use "\r\n" instead of PHP_EOL, although I think media players will be a ble to recognize any style of line breaks.

Categories