如何将文本输入写入文件中的新行?

时间:2018-04-21 21:12:43

标签: php newline textinput

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

 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.";
    }

1 个答案:

答案 0 :(得分:0)

也许这个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.