提取字符串的某个部分

时间:2013-03-12 15:59:24

标签: php string

我有一个数组,其中包含以下作为其值之一

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

我如何从那里提取2013年3月4日?这是一个动态领域,将永远在变化。我似乎无法找到正确的方法

我希望能够回显$ datepub;并且只是约会。

由于

2 个答案:

答案 0 :(得分:1)

一种非常简单的方法可能会爆炸它:

//dividing the string by whitespaces
$parts = explode(' ', $datepub);  

echo $parts[1]; //month (Mar)
echo $parts[2]; //day (04)
echo $parts[5]; //year (2013)

然后您可以使用createFromFormat函数将其转换为任何其他所需的格式:

//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

答案 1 :(得分:0)

使用Marc B代码示例扩展SimpleXML的答案:

$data = '<?xml version="1.0"?><meta itemprop="datePublished" content="Mon Mar 04 08:52:45 PST 2013"/>'; // your XML
$xml = simplexml_load_string($data);

// select all <meta> nodes in the document that have the "content" attribute
$xpath1 = $xml->xpath('//meta[@content]');
foreach ($xpath1 as $key => $node) {
    echo $node->attributes()->content; // Mon Mar 04 08:52:45 PST 2013
}

// Marc B's select "content" attribute for all <meta> nodes in the document
$xpath2 = $xml->xpath('//meta/@content');
foreach ($xpath2 as $key => $node) {
    echo $node->content; // Mon Mar 04 08:52:45 PST 2013
}
相关问题