从 URL 获取片段(哈希值“#”之后的值)

发布于 2024-08-22 19:04:03 字数 1436 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

青衫负雪 2024-08-29 19:04:03

如果您想获取用户浏览器中显示的哈希标记或锚点之后的值:这对于“标准”HTTP 来说是不可能的,因为该值永远不会发送到服务器(因此它在 中不可用>$_SERVER["REQUEST_URI"] 或类似的预定义变量)。您需要在客户端使用某种 JavaScript 魔法,例如将此值作为 POST 参数包含在内。

如果只是从任何来源解析已知的 URL,则 答案mck89 制作的 完全没问题。

If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.

If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.

那请放手 2024-08-29 19:04:03

该部分称为“片段”,您可以通过以下方式获取它:

$url = parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment

That part is called "fragment" and you can get it in this way:

$url = parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
心的位置 2024-08-29 19:04:03

A) PHP 中已经有带 #hash 的 url 了吗?简单的!简单解析一下吧!

if( strpos( $url, "#" ) === false ) echo "NO HASH !";
   else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0

或者在“旧”PHP 中,您必须预先存储分解后才能访问数组:

$exploded_url = explode( "#", $url ); $exploded_url[1]; 

B) 您想通过向 PHP 发送表单来获取 #hash 吗?
   =>使用一些 JavaScript 魔法! (预处理表单)

var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
    forms[i].addEventListener( // add a "listener"
        'submit', // for an on-submit "event"
        function () { //add a submit pre-processing function:
            var input_name = "fragment"; // name form will use to send the fragment
            // Try search whether we already done this or not
            // in current form, find every <input ... name="fragment" ...>
            var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
            if (hiddens.length < 1) { // if not there yet
                //create an extra input element
                var hidden = document.createElement("input");
                //set it to hidden so it doesn't break view 
                hidden.setAttribute('type', 'hidden');
                //set a name to get by it in PHP
                hidden.setAttribute('name', input_name);
                this.appendChild(hidden); //append it to the current form
            } else {
                var hidden = hiddens[0]; // use an existing one if already there
            }

            //set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
            hidden.setAttribute('value', window.location.hash);
        }
    );
}

根据您的 formmethod 属性,您可以通过以下方式在 PHP 中获取此哈希值:

$_GET['fragment']$_POST['fragment']

可能的回报: 1. ""< /code>[空字符串](无哈希) 2. 整个哈希,包括 #[hash] 符号(因为我们在 JavaScript 中使用了 window.location.hash这就是这样工作的:) )

C) 您想从请求的 URL JUST 获取 PHP 中的 #hash 吗?

                    sp;          你不能!

...(不在考虑常规 HTTP 请求时)...

...希望这有帮助:)

A) already have url with #hash in PHP? Easy! Just parse it out !

if( strpos( $url, "#" ) === false ) echo "NO HASH !";
   else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0

Or in "old" PHP you must pre-store the exploded to access the array:

$exploded_url = explode( "#", $url ); $exploded_url[1]; 

B) You want to get a #hash by sending a form to PHP?
    => Use some JavaScript MAGIC! (To pre-process the form)

var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
    forms[i].addEventListener( // add a "listener"
        'submit', // for an on-submit "event"
        function () { //add a submit pre-processing function:
            var input_name = "fragment"; // name form will use to send the fragment
            // Try search whether we already done this or not
            // in current form, find every <input ... name="fragment" ...>
            var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
            if (hiddens.length < 1) { // if not there yet
                //create an extra input element
                var hidden = document.createElement("input");
                //set it to hidden so it doesn't break view 
                hidden.setAttribute('type', 'hidden');
                //set a name to get by it in PHP
                hidden.setAttribute('name', input_name);
                this.appendChild(hidden); //append it to the current form
            } else {
                var hidden = hiddens[0]; // use an existing one if already there
            }

            //set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
            hidden.setAttribute('value', window.location.hash);
        }
    );
}

Depending on your form's method attribute you get this hash in PHP by:

$_GET['fragment'] or $_POST['fragment']

Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )

C) You want to get the #hash in PHP JUST from requested URL?

                                    YOU CAN'T !

...(not while considering regular HTTP requests)...

...Hope this helped :)

鹤舞 2024-08-29 19:04:03

我一直在寻找解决此问题的方法 - 我发现的唯一方法是使用 URL 重写来读取“锚点”。我在apache文档中找到了http://httpd.apache.org/docs/2.2/rewrite/advanced .html 以下...

默认情况下,重定向到 HTML 锚点不起作用,因为 mod_rewrite 会转义 # 字符,将其转换为 %23。
这反过来又破坏了重定向。

解决方案:在 RewriteRule 上使用 [NE] 标志。 NE 代表 否
逃脱。

讨论:这种技术当然也适用于其他特殊的
默认情况下,mod_rewrite 对 URL 进行编码的字符。

它可能还有其他警告,但我认为至少可以在服务器上使用 # 做一些事情。

I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...

By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.

Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.

Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.

It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.

别理我 2024-08-29 19:04:03

您无法获取井号标记之后的文本。它不会在请求中发送到服务器。

You can't get the text after the hash mark. It is not sent to the server in a request.

獨角戲 2024-08-29 19:04:03

如果你坚持想要 PHP 的值,我发现了这个技巧。
分割锚点(#)值并用JavaScript获取它,然后存储为cookie,然后用PHP获取cookie值

I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP

中性美 2024-08-29 19:04:03

如果您想从 URL 动态获取哈希值,这应该可行:

https://stackoverflow.com/a/57368072/2062851< /a>

<script>
    var hash = window.location.hash, //get the hash from url
    cleanhash = hash.replace("#", ""); //remove the #
    //alert(cleanhash);
</script>
<?php
    $hash = "<script>document.writeln(cleanhash);</script>";
    echo $hash;
?>

If you are wanting to dynamically grab the hash from URL, this should work:

https://stackoverflow.com/a/57368072/2062851

<script>
    var hash = window.location.hash, //get the hash from url
    cleanhash = hash.replace("#", ""); //remove the #
    //alert(cleanhash);
</script>
<?php
    $hash = "<script>document.writeln(cleanhash);</script>";
    echo $hash;
?>
挽心 2024-08-29 19:04:03

你可以通过 javascript 和 php 的组合来做到这

<div id="cont"></div>

一点

<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';

setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>

:然后,在表单提交时,您可以通过 $_POST['hash'] 检索值(设置表单)

You can do it by a combination of javascript and php:

<div id="cont"></div>

And by the other side;

<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';

setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>

Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)

|煩躁 2024-08-29 19:04:03

需要先解析url,所以是这样的:

$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

如果需要解析当前浏览器的实际url,就需要请求调用服务器。

$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

You need to parse the url first, so it goes like this:

$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

If you need to parse the actual url of the current browser, you need to request to call the server.

$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
疧_╮線 2024-08-29 19:04:03

获取查询字符串中哈希标记后面的数据很简单。以下是客户访问书中的术语表时使用的示例。它采用提供的名称锚点 (#tesla),并向客户提供该术语,并以蓝色突出显示该术语及其描述,以便于查看。

  1. 使用 div id 设置字符串,以便名称锚点位于其应有的位置,并且 JavaScript 可以更改文本颜色

    特斯拉
    ;
    一家能源公司
  2. 使用 JavaScript 来完成繁重的工作,可以在服务器端、插入 PHP 页面或任何地方。 .

    ;
    
  3. 加载页面时,我会自动启动 Java 函数。

    <前><代码><脚本>;
    $( 文档 ).ready(function() {

  4. 从服务器收到的 URL 中获取锚点 (#tesla)

    var myhash1 = $(location).attr('hash'); //myhash1 == #特斯拉
    
  5. 修剪其哈希符号

    myhash1 = myhash1.substr(1) //myhash1 == 特斯拉
    
  6. 我需要突出显示该术语和描述,以便创建一个新的变量

    var myhash2 = '1';
    myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
    
  7. 现在我可以操纵术语和描述的文本颜色

    var elem = document.getElementById(myhash1);
    elem.style.color = '蓝色';
    elem = document.getElementById(myhash2);
    elem.style.color = '蓝色';
    });
    
    
  8. 这有效。客户点击客户端的链接 (example.com#tesla) 并直接转到该术语。该术语和描述由 JavaScript 以蓝色突出显示,以便快速阅读。所有其他条目均保留为黑色。

Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.

  1. setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors

    <div id="tesla">Tesla</div>
    <div id="tesla1">An energy company</div>
    
  2. Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..

    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    
  3. I am launching the Java function automatically when the page is loaded.

    <script>
    $( document ).ready(function() {
    
  4. get the anchor (#tesla) from the URL received by the server

    var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
    
  5. trim the hash sign off of it

    myhash1 = myhash1.substr(1)  //myhash1 == tesla
    
  6. I need to highlight the term and the description so I create a new var

    var myhash2 = '1';
    myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
    
  7. Now I can manipulate the text color for the term and description

    var elem = document.getElementById(myhash1);
    elem.style.color = 'blue';
    elem = document.getElementById(myhash2);
    elem.style.color = 'blue';
    });
    </script>
    
  8. This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文