仅从URL检索类别ID


Retrieve only the category ID from URL

我的URL结构为www.site.com/listings/232-reality,其中232是类别ID,reality是我的类别名称。

我只想检索数字ID,用于使用类别ID从数据库中提取数据。我该怎么做?

您可以使用以下简单的东西:

<?php
preg_match_all('#('d+)#', $url, $matches);
$catid = $matches[0];
?>

但这并没有得到足够的检查。理想情况下,您希望在/:的基础上进行拆分

<?php
$elements = explode('/',$url);
$category = $elements[2];
$subelements = explode('-',$category);
$categoryid = intval($subelements[0]);
?>

您可以使用preg_replace:

id = preg_replace('/^.*'/([0-9]*)-[^'/]*$/','$1')

这假设url中的最后一个/就在类别ID之前。

如果232-real-estate存储在变量$var中,则可以使用获取ID

$id = strtok($var, '-');

顺便说一句,获得这个名称并不重要

$name = strtok(''); // returns: estate-agent