如何使用PHP获取URL字符串参数?

4
阅读了这里的许多文章后,我没有找到解决方案,所以我需要帮助来做到这一点... 我的URL如下 示例: 主页
https://mywebsite.com/
https://mywebsite.com/al/
https://mywebsite.com/it/
https://mywebsite.com/videos/
https://mywebsite.com/al/videos/
https://mywebsite.com/it/videos/
https://mywebsite.com/news/
https://mywebsite.com/al/news/
https://mywebsite.com/it/news/

查询

https://mywebsite.com/search/?q=YouTube
https://mywebsite.com/videos/search/?q=YouTube
https://mywebsite.com/news/search/?q=YouTube

https://mywebsite.com/al/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube
https://mywebsite.com/al/news/search/?q=YouTube

https://mywebsite.com/it/search/?q=YouTube
https://mywebsite.com/it/videos/search/?q=YouTube
https://mywebsite.com/it/news/search/?q=YouTube

我的PHP和HTML用于更改语言

<?php $Ava_Sulg = $_SERVER["REQUEST_URI"];?>

<a class="x" href="/<?php echo $Ava_Sulg;?>">EN</a>
<a class="x" href="/al<?php echo $Ava_Sulg;?>">AL</a>
<a class="x" href="/it<?php echo $Ava_Sulg;?>">IT</a>

所以我允许用户更改他们的语言,我想要做的是当他们更改语言时,URL 可以是上述之一,例如,如果他们将语言从 AL 更改为 IT ,并且 URL 是 https://mywebsite.com/al/videos/search/?q=YouTube,使用 PHP 我想要得到这个 https://mywebsite.com/it/videos/search/?q=YouTube,所以我只想从此 URL 更改 (/al/ to /it/) 或者例如从 IT to EN (/it/ to Nothing),但我想要更改的是在中间的部分,在主页上是不同的,这对我来说非常困难,我该怎么做,这可能吗?我希望在这里找到解决方案,如果可能的话!非常感谢。

非常感谢您的帮助,我已经修复了问题,但现在我无法输出视频标题和图像,即video:title和video:thumbnail_loc。 - Leo
video:title视频标题</video:title> video:description描述</video:description> </video:thumbnail_loc>图像</video:thumbnail_loc>video:duration302</video:duration> - Leo
<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> <url> <loc>https://视频发布网址/</loc> <video:video> <video:player_loc allow_embed="yes">https://嵌入式网址/</video:player_loc> <video:title>标题</video:title> <video:description>描述</video:description> <video:thumbnail_loc>图片.jpg</video:thumbnail_loc> <video:duration>384</video:duration> </video:video> </url> - Leo
6个回答

6

由于您只对路径组件感兴趣,因此您可以简单地使用parse_url来提取路径组件,而不是使用正则表达式:

function generateurl($url, $lc) {
    $parts = parse_url($url);
    $parts['path'] = preg_replace('@^/[a-z][a-z]/@', '/', $parts['path']);
    if ($lc !== 'en') {
        $parts['path'] = '/' . $lc . $parts['path'];
    }
    $url = '';
    if (isset($parts['scheme'])) $url .= $parts['scheme'] . '://';
    if (isset($parts['host'])) $url .= $parts['host'];
    if (isset($parts['port'])) $url .= ':' . $parts['port'];
    if (isset($parts['path'])) $url .= $parts['path'];
    if (isset($parts['query'])) $url .= '?' . $parts['query'];
    if (isset($parts['fragment'])) $url .= '#' . $parts['fragment'];
    return $url;
}

如果你有可用的http_build_url函数,上述函数可以被简化。函数输入和输出如下:
                           https://mywebsite.com/ + en = https://mywebsite.com/
                           https://mywebsite.com/ + al = https://mywebsite.com/al/
                           https://mywebsite.com/ + it = https://mywebsite.com/it/
                        https://mywebsite.com/al/ + en = https://mywebsite.com/
                        https://mywebsite.com/al/ + al = https://mywebsite.com/al/
                        https://mywebsite.com/al/ + it = https://mywebsite.com/it/

                    https://mywebsite.com/videos/ + en = https://mywebsite.com/videos/
                    https://mywebsite.com/videos/ + al = https://mywebsite.com/al/videos/
                    https://mywebsite.com/videos/ + it = https://mywebsite.com/it/videos/
                 https://mywebsite.com/al/videos/ + en = https://mywebsite.com/videos/
                 https://mywebsite.com/al/videos/ + al = https://mywebsite.com/al/videos/
                 https://mywebsite.com/al/videos/ + it = https://mywebsite.com/it/videos/

   https://mywebsite.com/videos/search/?q=YouTube + en = https://mywebsite.com/videos/search/?q=YouTube
   https://mywebsite.com/videos/search/?q=YouTube + al = https://mywebsite.com/al/videos/search/?q=YouTube
   https://mywebsite.com/videos/search/?q=YouTube + it = https://mywebsite.com/it/videos/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube + en = https://mywebsite.com/videos/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube + al = https://mywebsite.com/al/videos/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube + it = https://mywebsite.com/it/videos/search/?q=YouTube

                        /videos/search/?q=YouTube + en = /videos/search/?q=YouTube
                        /videos/search/?q=YouTube + al = /al/videos/search/?q=YouTube
                        /videos/search/?q=YouTube + it = /it/videos/search/?q=YouTube
                     /al/videos/search/?q=YouTube + en = /videos/search/?q=YouTube
                     /al/videos/search/?q=YouTube + al = /al/videos/search/?q=YouTube
                     /al/videos/search/?q=YouTube + it = /it/videos/search/?q=YouTube

在HTML中,我现在如何添加链接?<a class="x" href="/<?php echo $url;?>">EN</a>? - Leo
假设URL是绝对的,即以“https”或“/”开头,您需要<a class="x" href="<?php echo generateurl($url, 'en'); ?>">EN</a> - Salman A

4

首先,我建议您在URL中保留/en/以便更容易管理英语内容。

然后,要提取语言代码并替换为其他值,您可以使用:

您可以使用preg_replace(REGEX)

$url = "https://mywebsite.com/en/foo";
$codes = [ 'it', 'fr', ...]; 
$urls = [];
foreach($codes as $code){
    $urls[$code] = preg_replace("(https://mywebsite.com/)[a-z]{2}(.*)", "$1". $code. "$2", $url);
}

谢谢你的帮助,但我的网站上有20多种语言,我发现很难做到我想要的,因为我不太擅长脚本,只是喜欢尝试一些东西,但还是非常感谢你。 - Leo
如果你有多种语言,你只需要将两个选项中的一个(第二个选项推荐)放在一个foreach循环中即可。 - Chewie
我需要一些PHP代码来执行这个功能。例如,如果在域名URL https://mywebsite.com/ 后面是 /it/ 或者 /es/ 或者 /fr/,请将其删除。 - Leo
我更新了答案,向您展示如何使用foreach循环实现它的示例。 - Chewie
非常感谢您的帮助,但在这种情况下并不能帮助我。 - Leo
也许你可以尝试以更具体的方式解释你的问题。你想要实现什么,为什么这个解决方案对你没有帮助?你遇到了一个错误或者其他问题吗? - Chewie

2
我已经为您创建了一个可以实现此功能的函数。以下是其工作原理:
  1. 它从URL中删除所选语言及其后面的所有内容,将其放入$startUrl中。
  2. 获取原始URL并删除其中的第一部分(包括语言),将其放入$endUrl中。
  3. 将提供的语言添加到中间,并将所有三个部分组合在一起,命名为$newUrl,然后返回。

注意:该函数需要您在每个URL中指定语言,即使是英语也要这样做!

注意2:如果您将基本URL的结构从https://mywebsite.com/更改为https://mywebsite.com/public/之类的结构,则可能需要在函数的两个删除部分中更改$key值。我在代码中添加了关于它们所在位置的注释。


将"Original Answer"翻译成"最初的回答"。
function createUrl($url, $language){
    /*
    * FIX THE BEGINNING OF THE URL
    */
    // Explode the url into smaller parts and put into an array
    foreach((explode('/', $url)) as $key => $value){
        $expArray[$key] = $value;
    };

    // Remove the last part of the URL (including chosen language)
    foreach($expArray as $key => $value){
        if($key > 0){ /*<--This is one of the values you might need to be changed if your base url structure changes*/
            unset($expArray[$key]); 
        }
    }

    // Implode the array back to a string
    foreach($expArray as $key => $value){
        $startUrl = implode('/', $expArray);
    };

    

    /*
    * FIX THE END OF THE URL
    */
    // Explode the url into smaller parts and put into an array
    foreach((explode('/', $url)) as $key => $value){
        $expArray[$key] = $value;
    };

    // Remove the first part of the URL (including chosen language)
    foreach($expArray as $key => $value){
        if($key < 2){ /*<--This is the other value you might need to be changed if your base url structure changes*/
            unset($expArray[$key]); 
        }
    }

    // Implode the array back to a string
    foreach($expArray as $key => $value){
        $endUrl = implode('/', $expArray);
    };


    /* 
    * Put it all together
    */
    if(isset($endUrl)){
       $newUrl = $startUrl . $language . $endUrl;
       return $newUrl;
    }else{
       $newUrl = $startUrl . $language;
       return $newUrl;
    }
};

要在您的示例中使用它,您需要像这样编写:

<a class="x" href="<?php echo createUrl($_SERVER["REQUEST_URI"], '/EN/');?>"></a>
<a class="x" href="<?php echo createUrl($_SERVER["REQUEST_URI"], '/AL/');?></a>
<a class="x" href="<?php echo createUrl($_SERVER["REQUEST_URI"], '/IT/');?></a>

谢谢你的帮助,但是还是不行。当我从https://mywebsite.com/al/更改为例如https://mywebsite.com/it/时,它会跳转到这个链接https://mywebsite.com/al/it/。 - Leo
这可能是因为您使用的是 mywebsite.com/al 而不是 https://mywebsite.com/al。请相应地调整 $key 值。 - wenzzzel
好的,我已经在真正的Apache环境中尝试过了,而不是之前使用的php-fiddle工具,似乎我的浏览器(Chrome)会切掉https://部分。我已经更新了原始答案中的代码以适应这种情况,请再次尝试。另外,我还在代码底部添加了一个if语句,以防在使用短网址时出现错误。 - wenzzzel
谢谢您的帮助。 - Leo

2

替换URL是不好的做法。您应该将URL分为两个部分:

  1. 解析带语言和不带语言的URI
  2. 使用语言构建任何URI

例如,解析语言可能如下所示:

Original Answer翻译成:最初的回答
function extractLanguage($uri)
{
    if (preg_match('/^\/[a-z]{2}\//', $uri, $matches)) {
        $language = trim($matches[0], '/');
    } else {
       $language = ''; // or default language
    }   
    return $language;
}

extractLanguage('/search/?q=YouTube'); // will return empty string
extractLanguage('/al/search/?qURIuTube'); // will return 'al'

没有语言的URI解析可能会像这样:

最初的回答

function extractUri($uri)
{
    $uri= preg_replace('/^\/[a-z]{2}\//', '', $uri);
    if ($uri[0] !== '/') {
        $uri = '/' . $uri;
    }
    return $uri;
}

extractUri('/search/?q=YouTube'); // will return '/search/?q=YouTube'
extractUri('/al/search/?q=YouTube'); // will return '/search/?q=YouTube'

如果您将语言和URI分开,您可以使用以下函数构建目标URL,例如: buildTargetUrl()。原始答案翻译成中文为"最初的回答"。
function buildUri($path, $params = [], $language = '')
{
   $query = '';
   if (!empty($params)) {
       $query = '?' . http_build_query($params);
   }
   if (!empty($language)) {
       $language = '/' . $language ;
   } 
   return $language . $path . $query;
}

buildUri('/news/search', array('q' => 'YouTube')) // will return '/news/search/?q=YouTube'
buildUri('/news/search', array('q' => 'YouTube'), 'it') // will return 'it/news/search/?q=YouTube'

感谢您的帮助。 - Leo

1

我的解决方案!“不完美”,因为如果用户在https://example.com/es/news/search/?q=news上搜索内容,当我更改语言,例如从西班牙语(es)到英语(en),URL将会变成这样https://example.com/search/?q=news

if(isset($_GET["q"])) {
$qurl = $_GET["q"];
$surl = "/search/?q=";
}else{
$qurl = "";
$surl = "";
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接