1

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.

5
  • Show your current code example. Commented Oct 20, 2015 at 18:51
  • / needs to be urlencoded for the parse_str to work. Commented Oct 20, 2015 at 18:52
  • echo '<pre>'; parse_str($filename, $output); print_r($output); echo '<pre>'; Commented Oct 20, 2015 at 18:52
  • 1
    $filename is not defined in your comment. Edit your post and put a minimal reproducible example into it. Commented Oct 20, 2015 at 18:52
  • You can use parse_url() to extract the query string and then parse_str() to get at the arguments. Commented Oct 20, 2015 at 18:55

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

-1
$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

1 Comment

I have edited my answer to fit your request...but mainly parse_url is the function to go for..imho

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.