add hard quotes to a list strings [closed]
Lets say I 开发者_JAVA技巧have a text file with a list of strings
like so:
434242019884
434244064888
434240746884
434241083881
Using PHP what is the most efficient way to echo them back wrapped with hard quotes (')?
I'm just curious.
$lines = file('file.txt');
foreach($lines as $line){
echo "'".$line."'<br />";
}
<?php
$fh = fopen("file.txt", "r");
while(!feof($fh)) {
$line = fgets($fh);
echo "'".$line."'<br />";
}
fclose($fh);
?>
This will print your data properly, taking the newlines created by arrays into account.
Get the file contents. If there is more than one line of text in the file, it will create an array with each line as an item.
$lines = file('datafile.txt', );
Start a loop that puts each array item in a variable.
foreach($lines as $line) {
Trim the new line from the end of the string. ( \x0A = \n )
$line = trim($line, "\x0A" );
Echo the string, adding the newline where we want it.
echo "'".$line."'\n";
End the loop.
}
Here it is all at once:
$lines = file('datafile.txt', );
foreach($lines as $line) {
$line = trim($line, "\x0A" );
echo "'".$line."'\n";
}
how about:
echo "'" . str_replace(" ", "' '", $string) . "'";
EDIT: i did the code based on the spaces shown on your pre-edited message.. but you can change the space in the str_replace to an EOL
EDIT2: the $string is actually the whole list of strings, btw
This is how you do it using the explode/implode function in a single row:
<?php
echo "'".implode("'<br/>'", explode("\r\n", file_get_contents("file.txt")))."'";
?>
This could not work in case your file lines are divided by "\n" (Linux style) instead of "\r\n" (Windows style), just fix changing the "\r\n" explode parameter with "\n".
This way you can control the first and the last hardquotes (in case you don't want the last <br/>) and you relay to library functions.
I just don't know how fast is this compared with other solutions.
Edit: made some tests, performs perfectly (maybe also faster than other solutions).
精彩评论