简体   繁体   中英

Parse input string

I have a strings like this:

index.php?url=index/index
index.php?url=index/index/2&a=b

I'm trying to get this part of string: index/index or index/index/2.

I have tried parse_str function but not successful. Thanks.

You should be able to use $_SERVER['QUERY_STRING'] as shown below:

$url_params = $_SERVER['QUERY_STRING']; // grabs the parameter
$url_params = explode( '/', $url_params ); // seperates the params by '/'

which returns an array

Example index.php?url=index/index2 now becomes:

$url_params[ 0 ] =  index;
$url_params[ 1 ] =  index2;

Without more info:

// Example input
$input               = "index.php?url=index/index/2&a=b";
$after_question_mark = explode("=",$input)[1];
$before_ampersand    = explode("&",$after_question_mark)[0];
$desired_output      = $before_ampersand; // 'index/index/2'

More resilient option:

// Example input
$input               = "index.php?url=index/index/2&a=b";
$after_question_mark = explode("=",$input)[1];
if (strstr($after_question_mark, "&")){
    // Check for ampersand
    $before_ampersand    = explode("&",$after_question_mark)[0];
    $desired_output      = $before_ampersand; // 'index/index/2'
} else {
    // No ampersand
    $desire_output       = $after_question_mark;
}
$url = "index.php?url=index/index/2&a=b";
$query = parse_url($url, PHP_URL_QUERY);
$output = substr($query, $strpos($query, "=") + 1);
output: index/index/2&a=b

This will get you everything after the question mark

You can get more info on parse_url

or

$url = "index.php?url=index/index/2&a=b";
$output = substr($url, strpos("=") +1, $strrpos($url, "&") - strlen($url));
output: index/index/2

You dont need to break into an array to create overhead if you really just want to get a substring from a string

this will return false on no query string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM