PHP String Manipulation Functions: SUBSTR and STRPOS


This is a tutorial on string manipulation functions which are SUBSTR and STRPOS. Here is an example: How would you write a PHP script that will accept inputs as 1-Apr-10 but will output dates as 4/1/2010??? Can you script that out in 30 minutes?

Little bit tricky huh? There are a million ways to kill a tiger…Below is my approach (let $date be the input date)

<?php
//Find location of the first dash in the date
$firstdash = strpos($date,"-");
$startlookingseconddash=$firstdash+1;
//Get the day
$day = substr($date,0,$firstdash);
//Find location of the second dash
$seconddash = strpos($date,"-",$startlookingseconddash);
//Get the month
$monthdiff= $seconddash - $firstdash -1;
$month = substr($date,$startlookingseconddash,$monthdiff);
//Get year
$yearoffset=$seconddash+1;
$year= substr($date,$yearoffset,2);
//Get conversion for month
if ($month=='Jan') {
$monthconverted=1;
}
if ($month=='Feb') {
$monthconverted=2;
}
if ($month=='Mar') {
$monthconverted=3;
}
if ($month=='Apr') {
$monthconverted=4;
}
if ($month=='May') {
$monthconverted=5;
}
if ($month=='Jun') {
$monthconverted=6;
}
if ($month=='Jul') {
$monthconverted=7;
}
if ($month=='Aug') {
$monthconverted=8;
}
if ($month=='Sep') {
$monthconverted=9;
}
if ($month=='Oct') {
$monthconverted=10;
}
if ($month=='Nov') {
$monthconverted=11;
}
if ($month=='Dec') {
$monthconverted=12;
}
$date=$monthconverted.'/'.$day.'/'.'20'.$year;
$date=trim($date);
?>

So complex script. But I do complete this in 30 minutes, using my imagination, patience, complete understanding of the work and parameters of these important string functions: SUBSTR and STRPOS, and some trial and error.Do not criticize my script, as Word press says, Code is poetry.



Related posts: