【问题标题】:writing, reading and exploding txt file content写入、读取和分解txt文件内容
【发布时间】:2013-02-02 02:47:08
【问题描述】:

我有一个 textarea 和一个提交按钮,一旦我将内容写入 textarea 并按下按钮 - 它会将 textarea 内容写入 txt 文件,我需要帮助使用 explode 格式化该内容。 这是我用来将 textarea 内容写入 txt 文件的代码:

$tavalues = ($_POST['dname']); //dname is textarea field
$filename = "imones.txt";
$fp = fopen ($filename, "w");
if ($fp){
    fwrite($fp, $tavalues);
} 
fclose($fp);

如您所见,它写入了 imones.txt 文件。现在我想读取该文件内容,对其进行格式化,并将格式化的内容写入另一个文件。我似乎不知道如何为爆炸编写多个分隔符.. 这是我如何将数据输入到 textarea 的示例(全是逗号和其他东西):

example.com  example.com
 example.com, example.com
example.com

这是我希望它被格式化的方式(基本上我想删除 ',' , '\n', '\r'):

example.com
example.com
example.com

..(所有链接在一行中不带空格,注意链接不同不一样)

【问题讨论】:

    标签: php explode


    【解决方案1】:

    试试 PHP 的 preg_replace()

    【讨论】:

      【解决方案2】:

      如何将所有爆炸字符转换为一个而不是由此爆炸?!

      $expl = ';';
      $content = file_get_contents('imones.txt');
      $content = str_replace(',', $expl, $content);
      $content = str_replace('\n', $expl, $content);
      $content = str_replace('\r', $expl, $content);
      $content = str_replace(' ', $expl, $content);
      // ...
      
      while (strpos($content, "$expl$expl") !== false) { // while $expl is found twice
          $content = str_replace("$expl$expl", $expl, $content); // remove this
      }
      
      $parts = explode($expl, $content);
      
      // than join them
      $formatted = implode("\n", $parts);
      file_put_contents('somefile.txt', $formatted);
      

      【讨论】:

      • 由于某种原因,它用空格而不是换行符写入每个值,这就是我的意思 - 它这样写(example.com example.com example.com),我希望它写像这样(example.com\n example.com\n example.com\n(每个值都来自新行))
      • Linux 还是 Windows? Linux 换行符是“\n”,Windows 换行符是“\r\n”。可能这就是原因。
      • 似乎 "\r\n" 确实添加了换行符,但现在值之间有 2 个空格,就像这样 (example.com \nexample.com)
      • 可能需要加$content = str_replace(' ', $expl, $content);
      • 它删除了空格,但现在它在每个值之后添加了 2 个换行符
      【解决方案3】:

      也许试试这个。它又快又脏。为了获得更好的解决方案,您应该尝试使用正则表达式!

      $input = "exampleA.com  exampleB.com
       exampleC.com, exampleD.com
      exampleE.com";
      $tmp = explode(" ", $input);
      $str = "";
      $filename = "imones.txt";
      $fp = fopen ($filename, "w");
      if ($fp){
          for ($i = 0; $i < count($tmp); $i++) {
            if ($tmp[$i] != "") {
                $tmp[$i] = str_replace(",", "", $tmp[$i]);
                $tmp[$i] = trim($tmp[$i]);
                $str .= $tmp[$i]."\n";
            }
          }
      fwrite($fp, $str);
      } 
      fclose($fp);
      

      【讨论】:

      • 和上面的方法一样,由于某种原因,它也会在每个值之后给出 2x 新行
      • 每个值后有 2x 新行?对不起,我的盒子上没有这个。奇怪!
      • 这里也一样。这个例子有效。 Here it is in my test.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多