Month: April 2018

How to check valid date using PHP?

Sometime we need to check that date is valid or not, In many website input filed is date time so input date is valid or not need to check this. You can do this using php createFromFormat. This is simple demo code.

<?php
function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

echo '2018-04-27 12:12:12'.var_dump(validateDate('2018-04-27 12:12:12')); # true
echo '2018-04-32 12:12:12'.var_dump(validateDate('2018-04-32 12:12:12')); # false
echo '2018-04-30 12:12:61'.var_dump(validateDate('2018-04-30 12:12:61')); # false

Then Output is :

2018-04-27 12:12:12 : boolean true
2018-04-32 12:12:12 : boolean false
2018-04-30 12:12:61 : boolean false

You can also check date , this is demo code

<?php
function validateDate($date, $format = 'Y-m-d')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

echo '2018-04-27'.var_dump(validateDate('2018-04-27')); # true
echo '2018-04-32'.var_dump(validateDate('2018-04-32')); # false
echo '2018-04-30'.var_dump(validateDate('2018-04-30')); # false

Then Output is :

2018-04-27 : boolean true
2018-04-32 : boolean false
2018-04-30 : boolean true

If you face nay problem then please inform me. I will try to help you

Comment

automatic close open HTML tags in a string using php

In sometime in your string close tag missing in this case it need to close tag. This function help you

<?php

function closetags($html) {
    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);
    for ($i=0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)) {
            $html .= '</'.$openedtags[$i].'>';
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }
    return $html;
}

$str = '<div>This is some text<p> and here is a <strong>bold text then the post stop here....';
echo closetags($str);

This is result :

Normal text with missing close tag :
<div>This is some text<p> and here is a <strong>bold text then the post stop here....

Then result is :
<div>This is some text<p> and here is a <strong>bold text then the post stop here....</strong></p></div>

so this function automatic close tag.

Resource from :
https://stackoverflow.com/questions/3810230/close-open-html-tags-in-a-string

if you face any problem then please inform me.

Comment