开发者

add hard quotes to a list strings [closed]

开发者 https://www.devze.com 2023-03-22 21:42 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

  1. 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', );
    
  2. Start a loop that puts each array item in a variable.

    foreach($lines as $line)    {
    
  3. Trim the new line from the end of the string. ( \x0A = \n )

    $line = trim($line, "\x0A" );
    
  4. Echo the string, adding the newline where we want it.

    echo "'".$line."'\n";
    
  5. 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消