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

时间:2015-03-18 23:04:15

标签: php

我有网址: http://example.com/list4

我想在url名称中解析“list4”以获取分隔的字符串和数字。

最终的网址将是:

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

我现在能够做到这一点,但是:

当我尝试用$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];替换$ url时,无效。我试过$url = basename($_SERVER['REQUEST_URI']);但是也没有用......为什么?

2 个答案:

答案 0 :(得分:1)

试一试:

$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];

修改

为了满足问题的需要,您需要在网址末尾说明.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];

答案 1 :(得分:-1)

<?php

$网址= $ _ SERVER [ 'HTTP_HOST'] $ _ SERVER [ 'PHP_SELF'];

回声“

”;

$第一= preg_match_all( '/ [/] +([A-Z] )/?',$网址,$结果); $字符串= $结果[1] [0];

$第二= preg_match_all( '/ [/] + [A-Z] ([0-9] *)/?',$网址,$结果); $数= $结果[1] [0];

echo $ _SERVER ['HTTP_HOST']。$ string。$ number ?&GT;