这是我的代码,我希望从新行的文本字段中输入。例如,如果输入文本是名字和姓氏,那么我希望姓氏在新行上,并且我只有一个文本字段。我该怎么做?
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.";
}
也许这个解决方案是正确的
$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 Jamesn Smith'
'stack overflow' => Sorry, your name is not in correct format.
'John Smith' => 'Johnn Smith'
'John Johnson' => 'Johnn Johnson'
'JohnWilliams' => Sorry, your name is not in correct format.
'Stack Best Overflow' => 'Stack Bestn Overflow'
'Smith' => Sorry, your name is not in correct format.