Monday, April 20, 2009

Remove new line CRLF (\r\n) or line break

Removing the new line tags (CRLF) from a string

$string = "some thing new
line one
line two";

$new_string = preg_replace("/\r\n/", " ", $string);

you may also replace the line break with
tag as following

$new_string = preg_replace("/\r\n/", "
", $string);

Wednesday, February 25, 2009

Sorting an array by key on day, month, year or time


function date_compare($x, $y){
  $x = strtotime($x);
  $y = strtotime($y);
  if ($x == $y) return 0;
  return (($x > $y)?1:-1);
}
$array = array (
  'Jan 01, 2008' => 1,
  'Oct 31, 2008' => 10,
  'Nov 01, 2008' => 11,
  'Dec 01, 2008' => 12,
  'Jul 01, 2008' => 7,
  'Aug 01, 2008' => 8,
  'Sep 01, 2008' => 9,
);

Before sorting print the array

print_r($array);

Now Sort the array

uksort($array, 'date_compare');

After sorting print the array

print_r($array);

Sorting an array by time, date, month or year


function date_compare($x, $y){
  $x = strtotime($x);
  $y = strtotime($y);
  if ($x == $y) return 0;
  return (($x > $y)?1:-1);
}
$array = array (
 'Jan 01, 2008',
 'Oct 31, 2008',
 'Nov 01, 2008',
 'Dec 01, 2008',
 'Jul 01, 2008',
 'Aug 01, 2008',
 'Sep 01, 2008'
);

Before sorting print the array

print_r($array);

Now Sort the array

usort($array, 'date_compare');

After sorting print the array

print_r($array);