gpt4 book ai didi

php - 在没有 htaccess 或 mod_rewrite 的情况下解析 SEO 友好的 url

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:47:59 25 4
gpt4 key购买 nike

任何人都可以建议在 php 中的方法或不涉及 htaccess 或 mod_rewrite 的解析 SEO 友好 url 的函数吗?例子会很棒。

http://url.org/file.php/test/test2#3

返回:Array ( scheme] => http [host] => url.org [path] =>/file.php/test/test2 [fragment] => 3 )/file.php/test/test2

我将如何分离出/file.php/test/test2 部分?我想 test 和 test2 会成为参数。

编辑:

@Martijn - 在收到有关您的答案的通知之前,我确实弄清楚了您的建议。谢谢顺便说一句。这被认为是一种好的方法吗?

$url = 'http://url.org/file.php/arg1/arg2#3';
$test = parse_url($url);
echo "host: $test[host] <br>";
echo "path: $test[path] <br>";
echo "frag: $test[fragment] <br>";
$path = explode("/", trim($test[path]));
echo "1: $path[1] <br>";
echo "2: $path[2] <br>";
echo "3: $path[3] <br>";
echo "4: $path[4] <br>";

最佳答案

您可以使用 explode 从数组中获取零件:

$path = trim($array['path'], "/"); // trim the path of slashes
$path = explode("/", $path);
unset($path[0]); // the first one is the file, the others are sections of the url

如果你真的想让它再次从零开始,把它添加到最后一行:

$patch = array_values($path);

回应您的编辑:
你想让它尽可能灵活,所以没有基于最多 5 个项目的固定编码。虽然您可能永远不会超过那个,但不要将自己固定在它上面,只是您不需要的开销。

如果您有这样的页面系统:

id parent  name                url
1 -1 Foo foo
2 1 Bar, child of Foo bar-child-of-foo

做一个递归函数。将数组传递给一个函数,该函数使用第一部分来查找根项

SELECT * FROM pages WHERE parent=-1 AND url=$path[0]

该查询将返回一个 id,在父列中将其与数组的下一个值一起使用。取消设置 $path 数组的每个找到的值。最后,您将得到一个包含剩余部分的数组。

举个例子:

function GetFullPath(&$path, $parent=-1){
$path = "/"; // start with a slash
// Make the query for childs of this item
$result = mysqli_query($conn, "SELECT * FROM pages WHERE parent=".$parent." AND url=".current($path)." LIMIT 1");
// If any rows exists, append more of the url via recursiveness:
if($result->num_rows!==0){
// Remove the first part so if we go one deeper we start with the next value
$path = array_slice($patch,1); // remove first value
$fetch = $result->fetch_assoc();
// Use the fetched value to go deeper, find a child with the current item as parent
$path.= GetFullPath($path, $fetch['parent']);
}
// Return the result. if nothing is found at all, the result will be "/", probs home
return $path;
}

echo GetFullPath($path); // I pass it by reference, any alterations in the function happen to the variable outside the scope aswell

这是一个草稿,我没有对此进行测试,但你明白我正在尝试绘制草图。您可以使用相同的方法获取您所在页面的 ID。只需继续将变量传递回来 c

有一天我掌握了递归的诀窍 ^^。
再次编辑:糟糕,原来是一些代码。

关于php - 在没有 htaccess 或 mod_rewrite 的情况下解析 SEO 友好的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20076144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com