如何使用哈希提取URL参数?

时间:2012-07-31 08:28:15

标签: php javascript url parameters

  

可能重复:
  Why the hash part of the URL is not in the server side?

我有一个网址http://www.example.com/edit-your-profile/#file%5B0%5D%5Bstatus%5D=Complete&file%5B0%5D%5BremoteFileURL%5D=http%3A%2F%2Fi.imgur.com%2Fe0XJI.jpg&file%5B0%5D%5BfileSource%5D=Previous%20Uploads&file%5B0%5D%5BpicID%5D=p43

我需要在页面上回显或显示“remoteFileURL”参数作为输入字段的值,看来我不能用PHP(据我所知)这样做。我不太了解js,任何帮助都会受到赞赏!

5 个答案:

答案 0 :(得分:3)

简化 - 不是美...只是为了展示一种可能性并指出你正确的方向。返回http://i.imgur.com/e0XJI.jpg

<?php
$url = 'http://www.example.com/edit-your-profile/#file%5B0%5D%5Bstatus%5D=Complete&file%5B0%5D%5BremoteFileURL%5D=http%3A%2F%2Fi.imgur.com%2Fe0XJI.jpg&file%5B0%5D%5BfileSource%5D=Previous%20Uploads&file%5B0%5D%5BpicID%5D=p43';
$urlDecoded = urldecode($url);
$urlParts = parse_url($urlDecoded);

$matches = array();
$regexRemoteUrl = preg_match('/remoteFileUrl\]=([^&]+)/i', $urlParts['fragment'], $matches);
// remoteFileURL
echo($matches[1]);
?>

答案 1 :(得分:0)

您可以使用正则表达式搜索与“remoteFileUrl”匹配的任何内容,后跟一些字符...然后在每个&符号处拆分字符串...然后将该文本字符串回显到输入字段中。

答案 2 :(得分:0)

如果您想在Javascript中使用它,那么这里只需要一些正则表达式,它将为您提供:

decodeURI(window.location.hash).match(/remoteFileURL]=([^&]+)/)[1]

它为我返回"http%3A%2F%2Fi.imgur.com%2Fe0XJI.jpg"

所以我们使用unescape

unescape(decodeURI(window.location.hash).match(/remoteFileURL]=([^&]+)/)[1])

获取"http://i.imgur.com/e0XJI.jpg"

答案 3 :(得分:0)

var decodedUri = decodeURIComponent('http%3A%2F%2Fdtzhqpwfdzscm.cloudfront.net%2F4ca06373624db.jpg');

您可以使用此功能从网址中提取您需要的参数。

function getURLParameter(name,url) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(decodedUri)||[,null])[1]
    );
}

按如下方式调用该功能

 var fileUrl = getURLParameter("remoteFileURL",decodedUri);

:)

答案 4 :(得分:0)

这是一个可以在JavaScript或php中使用的正则表达式:

(?:file%5B0%5D%5BremoteFileURL%5D|remoteFileURL)=(.+?)&

由于您的示例网址有一种非常奇怪的命名参数形式,因此我包含了该表单和常用方法。它匹配file[0][remoteFile]以及remoteFile并捕获该参数的值。

在JavaScript中,您可以这样做,如果有一个字段包含ID为URL的网址。

var url = document.getElementById('URL').value;
var myRegexp = /(?:file%5B0%5D%5BremoteFileURL%5D|remoteFileURL)=(.+?)\&/;
var match = myRegexp.exec(url);
alert(match[1]);
相关问题