簡體   English   中英

如何使用preg_match從url獲取字符串?

[英]How to get a string from url using preg_match?

我想使用php preg_match從url中提取id ..

例如: $string = 'http://www.mysite.com/profile.php?id=1111'; : $string = 'http://www.mysite.com/profile.php?id=1111'; 我需要輸出'1111'

使用preg_match。

我試過這個:

if(preg_match('/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=[0-9]/', $string, $match) > 0){

    $id =  $match[1];
}

但我輸出為' profile.php '

有人能幫助我嗎?

為什么不在parse_str使用parse_url

$url_component = parse_url($string);
parse_str($url_component['query'], $output);
echo $output['id'];
$pattern = '/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=([0-9]+)/';

這應該工作正常! 但是使用parse_url執行此操作

如果url中只有一個參數,你可以使用explode函數輕松完成,比如

$string = 'http://www.mysite.com/profile.php?id=1111';
$ex=explode('=',$string);
$id=$ex[1];

你也可以使用php的parse_url函數。

希望這有幫助,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM