Tutorial :PHP replace string



Question:

$name (string) gives something like (possible value):

John II, Litten Draw  

We should update $name in two steps:

  1. Catch the words before first comma and throw them to the end of the string
  2. Remove first comma
  3. Create a file 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".

Thanks.


Solution:1

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.


Solution:2

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


Solution:3

This regex should do it for you...

preg_replace('#\\b(\\w+),\\s*(\\w+)\\b#', '\\2 \\1', $string);  

Basically, it's looking for:

  1. A word boundry (the \\b part)
  2. Then one or more word characters (the \\w+ part)
  3. Then a comma followed by zero or more whitespace characters (,\\s*)
  4. Then one or more word characters (the \\w+ part)
  5. Finally, another word boundry...


Solution:4

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);  


Solution:5

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »