Removing date from string in PHP - php

I am trying to remove all dates from strings in PHP using preg_replace(). The dates are of the following formats: YYYY-MM-DD, YYYY/MM/DD or YYYY.MM.DD
$string1 = "Current from 2014-10-10 to 2015-05-23";
$output = preg_replace('/\d{4}[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])/g', '', $string1);
Expected output is "Current from to ". Currently I am getting back "".
Any help greatly appreciated! Wonko

This should work.
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.02.10";
$output = preg_replace('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', '', $input);
echo $output;
Update
To ensure that the date also is valid
<?php
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.19.10";
$output = preg_replace_callback('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', function($matches) {
$date = str_replace(array('.','/'), '-', $matches[1]);
$newDate = DateTime::createFromFormat('Y-m-d', $date);
if($newDate->format('Y-m-d') == $date) {
return false;
}else {
return $matches[1];
}
}, $input);
echo $output;

Related

One explode function for two date formats

I have two PHP variable $consult_date_arr and $consultationdate.the user can insert any date format consider for now 22-12-2014 or 22/12/2014.what i want to do is i want to write a explode function which should work for both the condition i.e. for both the date formats.
$consult_date_arr=explode("/",$consultationdate);
$consult_date_arr=explode("-",$consultationdate);
The explode function should be the combination of above two explode function in functionality,such date it works for both the formats.if any doubt please let me know.
thanks in advance.
try something like this
<?php
$date = '22/12/2014';
$keywords = preg_split("/[-,\/]+/", $date);
print_r($keywords);
?>
preg_split — Split string by a regular expression
REFERENCE
http://php.net/manual/en/function.preg-split.php
<?php
$dt = "1992-05-30";
//$dt = "1992/05/30";
function expld($date){
$date = str_replace("/", "-", $date);
$date = explode("-",$date);
return $date;
}
$newdate = expld($dt);
echo $newdate[0];
?>
you can write custom function and call explode inside it
like
$string = "-" OR "/" Or whatever you want to explode with
function dateFormat($string,$date)
{
$consult_date_arr=explode($string,$consultationdate);
return $consult_date_arr;
}
you will need regular expression, using preg_match in php.
<?php
$consult_date_arr;
$consultationdate = '22/12/2014';
if(preg_match('/[\d]{2}-[\d]{2}-[\d]{4}/', $consultationdate)){
$consult_date_arr = explode('-', $consultationdate);
}else if(preg_match('/[\d]{2}\/[\d]{2}\/[\d]{4}/', $consultationdate)){
$consult_date_arr = explode('/', $consultationdate);
}
var_dump($consult_date_arr);
?>
Hi check the code below,
<?php
if(!function_exists('date_explode')){
function date_explode($date){
$explode_date = array();
$delimiter = '';
if(strstr($date, '/')){
$delimiter = '/';
}elseif(strstr($date, '-')){
$delimiter = '-';
}
if(!empty($delimiter)){
$explode_date = explode($delimiter, $date);
}
return $explode_date;
}
}
$consult_date_arr=date_explode('22-12-2014');
print_r($consult_date_arr);
$consult_date_arr=date_explode('22/12/2014');
print_r($consult_date_arr);
?>
fiddle example
P.S.: Please do validation its a must, validation will prevent you from this type of issues

conditional preg_replace for optional backreference replacement

I have a regex to reformat a date from "dd/mm/yyyy HH:ii:ss" to YYYY-MM-DD HH:II:SS which is fine, but I would also use the same for validating date only (when no hours are provided).
Maybe there is a way to give default value to the replacement but I didn't found it.
$regex = '#^(\d{2})/(\d{2})/(\d{4})(?: (\d{2}):(\d{2})(?::(\d{2}))?)?$#';
$replace = '$3-$2-$1 $4:$5:00';
$str = '07/11/2013 20:30';
$val = preg_replace($regex, $replace, $str);
echo $val; // "2013-11-07 20:30:00"
$str = '07/11/2013';
$val = preg_replace($regex, $replace, $str);
echo $val; // "2013-11-07 ::00"
You can use preg_replace_callback and provide a custom callback method to perform the replacement. Inside you're callback, you can apply your default values:
$regex = '#^(\d{2})/(\d{2})/(\d{4})(?: (\d{2}):(\d{2})(?::(\d{2}))?)?$#';
$replace = function ($m) {
if (!$m[4]) $m[4] = '00';
if (!$m[5]) $m[5] = '00';
return "$m[3]-$m[2]-$m[1] $m[4]:$m[5]:00";
};
$str = '07/11/2013 20:30';
$val = preg_replace_callback($regex, $replace, $str);
echo $val; // "2013-11-07 20:30:00"
$str = '07/11/2013';
$val = preg_replace_callback($regex, $replace, $str);
echo $val; // "2013-11-07 00:00:00"
To validate date and time try this:
$regex = '(\d{2})/(\d{2})/(\d{4}) (\d{2}):(\d{2}):(\d{2})';

Why does my function add an extra dash to this URL? ( PHP:Regex)

function convert($raw) {
$new = preg_replace("![^a-z0-9]+!i", "-", $raw);
return $new;
}
The functon turns "a boy" into "a-boy-" when i run it, but i want "a-boy" how do I modify the regex to take care of this problem?
Thanks!
function convert($raw) {
$new = preg_replace("![^a-z0-9]+!i", "-", $raw);
$new = rtrim($new,'-');
return $new;
}
Check this out it works fine
function convert($raw) {
$new = preg_replace("![^a-z0-9]+!i", " ", $raw);
return $new;
}
$data ="a - boy";
echo convert($data);

Extract multiple date format from few string variables in php

I need to extract the date out of a string variable, and the date are formatted in various kind of formats as below:
$date1 = "03/12/2011 (Sat)";
$date2 = "3.12.2011 SAT";
$date3 = "Date: 03/12/2011 "; /* <-- the extra trailing space is intentional */
$date4 = "date:03/12/2011";
$date5 = "date: 03/12/2011";
$date6 = "03/12/2011";
$date7 = "13.12.2011 TUE";
What is the best way to create a PHP function which will work for all the input variables above in extracting the correct date info?
For more info on the DateTime object returned by the function, check the PHP documentation for the DateTime class.
/**
* Parses date from string
* #param string $str Uncorrected date string
* #return DateTime PHP datetime object
*/
function date_grab($str)
{
// regex pattern will match any date formatted dd-mm-yyy or d-mm-yyyy with
// separators: periods, slahes, dashes
$p = '{.*?(\d\d?)[\\/\.\-]([\d]{2})[\\/\.\-]([\d]{4}).*}';
$date = preg_replace($p, '$3-$2-$1', $str);
return new \DateTime($date);
}
// verify that it works correctly for your values:
$arr = array(
"03/12/2011 (Sat)",
"3.12.2011 SAT",
"Date: 03/12/2011 ", /* <-- the extra trailing space is intentional */
"date:03/12/2011",
"date: 03/12/2011",
"03/12/2011"
);
foreach ($arr as $str) {
$date = date_grab($str);
echo $date->format('Y-m-d') . "\n";
}
you can use the below function, it will match all the variables you spcecified.
function extractDates($mydate)
{
$date = explode(" ", $mydate);
$output = $date[0];
if ($date[0] == "Date:" || $date[0] == "date:")
{
$output = $date[1];
}
return $output;
}
$date1 = "Date: 03/12/2011";
echo extractDates($date1);
The output will be as you expected: "03/12/2011".
You can also test all your strings:
$date1 = "03/12/2011 (Sat)";
$date2 = "3.12.2011 SAT";
$date3 = "Date: 03/12/2011 "; /* <-- the extra trailing space is intentional */
$date4 = "date:03/12/2011";
$date5 = "date: 03/12/2011";
$date6 = "03/12/2011";
$date7 = "13.12.2011 TUE";

String translate from Array , str_replace?

String translate from Array , str_replace?
I have an array
$money = array(
"USD"=>100,
"BAT"=>1000,
"RIEL"=>2000
);
And I define as constant to be translate:
define("const_infor","Your __TYPE__ are: __AMOUNT__ __CURRENCY__ .<br><br>");
Bad WAYS:
echo "Your balance are :";//more constant here
foreach ($money as $currency=>$amount){
echo $money.$currency."; ";
}
I try to output(GOOD WAYS):
$tmp1 = "";
$tmp2 = "";
foreach ($money as $currency=>$amount){
$tmp1 .= $money;
$tmp2 .= $currency;
}
echo str_replace(ARRAY("__TYPE__","__AMOUNT__","__CURRENCY__"),ARRAY("Balance",$tmp1,$tmp2),const_infor);
BUT What I want is the output should be :
Your Balance are: 100 USD; 1000 BAT; 2000 RIEL
How can I pass the $currency. to str_replace ?
Anyone can help me to do this.?
I don't know what exactly you wanna do but if it's only output
try
printf("Your Money %f %f %f", $money["USD"], $money["BAT"], $money["RIEL"]);
Well, below is just kind of a parser for doing what you want.. Try and see if it fits your needs:
function replace($string, $name = '', $value = '')
{
if ( !empty($name) )
{
str_replace('{'.$name.'}', $value, $string);
}
}
$string = 'Your balance is {bal1} USD, {bal2} BAT';
$string = replace('bal1', $money['USD'], $string);
$string = replace('bal2', $money['BAT'], $string);
$string = replace('bal3', $money['GBP'], $string);
print $string;
try that:
foreach ($money as $key => $cur)
echo $cur.' '. $key;

Categories