我有一个HTML表单字段$_POST["url"],有一些url字符串作为值。

举例如下:

https://example.com/test/1234?email=xyz@test.com
https://example.com/test/1234?basic=2&email=xyz2@test.com
https://example.com/test/1234?email=xyz3@test.com
https://example.com/test/1234?email=xyz4@test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5@test.com

etc.

如何从这些url /值中只获得电子邮件参数?

请注意,我不是从浏览器地址栏获取这些字符串。


当前回答

$web_url = 'http://www.writephponline.com?name=shubham&email=singh@gmail.com';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);

echo "Name: " . $queryArray['name'];  // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:singh@gmail.com

其他回答

之后的所有参数?可以使用$_GET数组访问。所以,

echo $_GET['email'];

将从url中提取电子邮件。

$uri = $_SERVER["REQUEST_URI"];
$uriArray = explode('/', $uri);
$page_url = $uriArray[1];
$page_url2 = $uriArray[2];
echo $page_url; <- See the value

这对我来说使用PHP非常有用。

为此,您可以使用parse_url()和parse_str()。

$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];

如果你想用PHP动态获取$url,看一下这个问题:

获取完整的PHP URL

$web_url = 'http://www.writephponline.com?name=shubham&email=singh@gmail.com';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);

echo "Name: " . $queryArray['name'];  // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:singh@gmail.com

在Laravel中,我使用:

private function getValueFromString(string $string, string $key)
{
    parse_str(parse_url($string, PHP_URL_QUERY), $result);

    return isset($result[$key]) ? $result[$key] : null;
}