PHP - 如何从URL获取ID

时间:2013-10-03 14:07:56

标签: php url explode

我有2个网址 -

$url="http://www.mysite.com/index.php?topic=23180.new#new";
$url="http://www.mysite.com/index.php/topic,23180.0.html";

在这两个网址之上,我没有在导航栏中检索到这个。这是从数据库表中检索并放入一个变量$url

我想从两个网址上方获取23180主题ID。

现在如何获取此主题ID?

1 个答案:

答案 0 :(得分:1)

我应该尝试使用正则表达式...比如:

/**
 * Locate and extract topic id from url received on this function.
 *
 * http://www.mysite.com/index.php?topic=23180.new#new
 * http://www.mysite.com/index.php/topic,23180.0.html
 *
 * @param string Url that must be located.
 * @return string Return that id located at string.
 * @example
 * <?php
 *     // must print 23180
 *     echo getTopicId("http://www.mysite.com/index.php?topic=23180.new#new");
 * ?>
 */
function getTopicId($urlString)
{
    return preg_replace('/topic(?:\=|\,)([0-9]+)\./i', '$1', $urlString);
}