Reputation: 43647
$name
(string) gives something like (possible value):
John II, Litten Draw
I want to update $name
in two steps:
current_name.txt
(or update if already exists) and throw to it source of $name
"John II, Litten Draw" should be replaced with "Litten Draw John II".
How can I do this?
Upvotes: 0
Views: 409
Reputation: 47894
I would certainly use preg_replace()
for the mutation and file_put_contents()
to append the new date with a trailing newline.
Capture the leading non-comma characters as capture group 1, then match a comma followed by optional whitespace characters, then capture the remainder of the string as capture group #2.
Code:
$name = "John II, Litten Draw";
file_put_contents(
'current_name.txt',
preg_replace('/^([^,]+),\s*(.+)$/', '$2 $1', $name) . PHP_EOL,
FILE_APPEND
);
Upvotes: 0
Reputation: 28883
Like this?
$split = explode(",", $name, 1);
$name = trim($split[1]) . " " . trim(split[0]);
Then it's just basic file I/O.
If you have a list of words (assuming they are all on separate lines):
$list = explode("\n", $names);
$nnames = "";
foreach($list as $name)
{
$split = explode(",", $name);
$nnames .= trim($split[1]) . " " . trim(split[0]) . "\n";
}
Upvotes: 4
Reputation: 53940
regular expressions are the way to go here
$a = "Obama, Barak";
echo preg_replace('~(\w+)\W+(\w+)~', "$2 $1", $a);
also works for multiple names:
$a = "
Obama, Barak
Federer, Roger
Dickens, Charles
";
echo preg_replace('~(\w+)\W+(\w+)~', "$2 $1", $a);
Upvotes: 2
Reputation: 54445
Here's some sample code that should work OK:
<?php
function getCanonicalName($name) {
// Check for the existance of a comma and swap 'elements' if necessary.
if(strpos($name, ',') !== false) {
list($surname, $forename) = explode(',', $name);
$name = $forename . ' ' . $surname;
}
// Trim the name.
return trim($name);
}
// Test data and file I/O.
$outputData = '';
$testData = array('Obama, Barak', 'Federer, Roger', 'John Parker');
foreach($testData as $name) {
$outputData .= getCanonicalName($name) . "\n";
}
file_put_contents('current_name.txt', $outputData, FILE_APPEND);
?>
Incidentally, this (like all of the solutions currently attached to your question) will cause data loss if there's more than one comma in $name. As such, if this is possible you should update getCanonicalName to cater for this eventuality.
Upvotes: 1
Reputation: 165201
This regex should do it for you...
preg_replace('#\\b(\\w+),\\s*(\\w+)\\b#', '\\2 \\1', $string);
Basically, it's looking for:
\\b
part)\\w+
part),\\s*
)\\w+
part)Upvotes: 2
Reputation: 175375
See strpos
to find the comma, ltrim
to remove the whitespace, and fopen
with the mode a
to append to the file. You can also use explode
to split around the comma, which is usually easier
Upvotes: 1