在php/wordpress中从url解析日期

f0ofjuux  于 2022-12-21  发布在  PHP
关注(0)|答案(3)|浏览(112)

我有一个包含yyyy-mm-dd格式的日期的URL,如何在PHP中解析该URL以获取日期?
URL示例:http://example.com/nepal/events/visit-nepal-2020/2020-01-09

ogsagwnx

ogsagwnx1#

你可以在$_SERVER['REQUEST_URI']上使用正则表达式,这将得到请求URI中出现的第一个YYYY-MM-DD格式的日期:

preg_match('/\/(\d{4}-\d{2}-\d{2})[\/]?/', $_SERVER['REQUEST_URI'], $match);
$date = ($match) ? $match[1] : null;

如果没有找到日期,则$date将包含null;

a9wyjsp7

a9wyjsp72#

如果您需要从URL获取日期的最后一个值,请检查下面的代码

$str = 'http://example.com/nepal/events/visit-nepal-2020/2020-01-09';
$id = substr($str, strrpos($str, '/') + 1);
$date = date('Y-m-d',strtotime($id));
echo $date;
4ioopgfo

4ioopgfo3#

要在PHP中解析URL中的日期,可以使用'parse_url'函数获取URL的路径,然后使用'explode'函数通过'/'字符将路径拆分为数组。然后,可以获取数组的最后一个元素,该元素应为格式为'yyyy-mm-dd'的日期,并使用DateTime类将日期解析为PHP DateTime对象。
下面是一个示例,说明如何执行此操作:

$url = 'http://example.com/nepal/events/visit-nepal-2020/2020-01-09';

// Use parse_url to get the path of the URL
$path = parse_url($url, PHP_URL_PATH);

// Split the path into an array by the '/' character
$path_parts = explode('/', $path);

// Get the last element of the array, which should be the date
$date_string = end($path_parts);

// Use DateTime to parse the date
$date = new DateTime($date_string);

// You can now use the $date object to work with the date in PHP
echo $date->format('Y-m-d');  // Outputs "2020-01-09"

相关问题