如何在php中解析url以获取数字和字符串


How to parse url in php to get numbers and strings

我有url:http://example.com/list4

我想解析url名称中的"list4"以获得分隔的字符串和数字。

最终url将是:

<?php  echo  'http://example.com/'.$string.$number; ?>

我现在可以做到,但是:

当我尝试用$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];替换$url时,它不起作用。我试过$url = basename($_SERVER['REQUEST_URI']);,但不太管用。。。为什么?

尝试一下:

$url = "http://example.com/list4";
preg_match("#'/('w+)('d+)$#", $url, $matches);
echo "String: " . $matches[1] . "<br>";
echo "Number: " . $matches[2] . "<br>";
// print out the URL you wanted above
echo "http://example.com/" . $matches[1] . $matches[2];

编辑

为了满足问题的需要,您需要在URL末尾说明.php。这将起作用:

$url = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
preg_match("#'/('w+)('d+)'.?'w*$#", $url, $matches); // updated
echo "String: " . $matches[1] . "<br>";
echo "Number: " . $matches[2] . "<br>";
// print out the URL you wanted above
echo "http://example.com/" . $matches[1] . $matches[2];
<?php

$url=$_SERVER['HTTP_HOST']$_服务器['hp_SELF'];

echo"

";

$first=preg_match_all('/.[/]+([a-z])?/'$url,$result);$string=$result[1][0];

$second=preg_match_all('/.[/]+[a-z]([0-9]*)?/'$url,$result);$number=$result[1][0];

echo$_SERVER['HTTP_HOST']$字符串$数字?>