【问题标题】:How to write text input to new line in file?如何将文本输入写入文件中的换行符?
【发布时间】:2018-10-02 06:28:13
【问题描述】:

这是我的代码,我想从新行的文本字段中输入。例如,如果输入文本是名字和姓氏,那么我希望姓氏在新行上,并且我只有一个文本字段。我该怎么做?

 if (isset($string) and (bool)preg_match('/[A-Z]/', $string) == TRUE) {
    //if yes, it is writing it into file
    $myfile = fopen("names.txt", "w") or die("Unable to open file!");
    $txt = $string;
    fwrite($myfile, $txt);

    fclose($myfile);
    }
    else {
        echo "Sorry, your name is not in correct format.";
    }

【问题讨论】:

  • 您可以使用PHP_EOL"\n",但您必须先对$string 执行此操作,然后再将其写入文件。所以告诉我们你是如何创建$string
  • $string = $_POST["names"] 这就是我创建 $string 的方式。这是在上面的 if 语句之前
  • 那么你将不得不定义$_POST["names"] 的内容并且......例如......用换行符替换名称之间的空格。但要做到这一点,你必须确保 a) 实际上是一个空格 b) 确保只有一个空格 c) 等等
  • 好的。 First and Last 这只是我正在使用的文本输入。如果我使用两个文本输入,则 PHP_EOL 和 "\n" 有效。但不是单文本输入
  • 我打算建议您将该字段分成 2 个单独的字段。所以使用那个方法

标签: php newline textinput


【解决方案1】:

也许这个solution 是真的

$names = [
    's34S$2 John',
    'John James Smith',
    'stack overflow',
    'John Smith',
    'John Johnson',
    'JohnWilliams',
    'Stack Best Overflow',
    'Smith'
];

$delimiter = '\n'; // "\n" for real use

foreach($names as $name){

    $newName = preg_replace(
        '/^([A-Z][a-z]+([\ ][A-Z][a-z]+)*)([\ ][A-Z][a-z]+)+$/',
        "$1$delimiter$3",
        $name
    );

    if ( $newName != $name ){
        echo "'$name' => '$newName'\n";
        // file_put_contents("names.txt", $newName); for real use
    } else {
        echo "'$name' =>  Sorry, your name is not in correct format.\n";
    }

}

输出:

's34S$2 John' =>  Sorry, your name is not in correct format.
'John James Smith' => 'John James\n Smith'
'stack overflow' =>  Sorry, your name is not in correct format.
'John Smith' => 'John\n Smith'
'John Johnson' => 'John\n Johnson'
'JohnWilliams' =>  Sorry, your name is not in correct format.
'Stack Best Overflow' => 'Stack Best\n Overflow'
'Smith' =>  Sorry, your name is not in correct format.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-14
    • 2017-05-31
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多