Search code examples
phpstringhtml-parsingmeta-tagstext-extraction

Get the content attribute value from a <meta> tag with a specified itemprop attribute value from an HTML string


I have an array which contains the following as one of its values:

<meta itemprop="datePublished" content="Mon Mar 04 08:52:45 PST 2013"/>

How do I extract the March 4th 2013 out of there? This is a dynamic field and will always be changing. I can't seem to find the right way to do it.

I want to be able to just echo $datepub; and just have the date.


Solution

  • A very simple way could be exploding it:

    //dividing the string by whitespaces
    $parts = explode(' ', $datepub);  
    
    echo $parts[1]; //month (Mar)
    echo $parts[2]; //day (04)
    echo $parts[5]; //year (2013)
    

    Then you could make use of createFromFormat function to convert it to any other desirable format:

    //creating a valid date format
    $newDate = DateTime::createFromFormat('d/M/Y', $parts[1].'/'.$parts[2].'/'.$parts[5]);
    
    //formating the date as we want
    $finalDate = $newDate->format('F jS Y'); //March 4th 2013