-1

I am trying to echo some part of a string, the string is for example:

"?page=tournament&action=brackets&tournID=2"

I am not using URL so I cannot use $_GET. Only string. I want to get the first and second element after "="

Thus should return

$first = tournament

$second = brackets (should not return &tournID=2)

Or second example

index.php?page=users&action=online

$first = users
$second = online

I have tried using explode without success

$urlArray = explode('=',$user['page']);

it is returning "?page"

Thanks in advance..

Karim Ali
  • 11
  • 1
  • Use `$_GET` of php if `?page=tournament&action=brackets&tournID=2` coming from url. – Manwal Dec 10 '14 at 05:16
  • @Manwal one can use the $_GET array if the string happens to be the query string of the URL to the php script, but maybe the string comes from somewhere else and needs parsing in code. @Karim maybe show some more code around the explode() that you tried. You are on the right track, sort of. But you really need to split the string at both `=` and `?` characters, so regexp might be a better fit. – RobP Dec 10 '14 at 05:19
  • 1
    You want to *parse a URL* or *parse a query string*. There are functions specifically for that task already, don't reinvent the wheel. – deceze Dec 10 '14 at 05:22

1 Answers1

0

You can use $_GET to get those variables:

$page = $_GET['page'];
$action = $_GET['action'];

If you only have a string use this snippet:

$tmp_arr = explode("&", substr($string, 1));
foreach($tmp_arr as $var)
{
    $ans_arr = explode("=", $var);
    if($ans_arr[0] == "page")
    {
        $page = $ans_arr[1];
    }
    if($ans_arr[0] == "action")
    {
        $action = $ans_arr[1];
    }
}
LostPhysx
  • 3,573
  • 8
  • 43
  • 73
  • I Cannot because it is a string not in URL. – Karim Ali Dec 10 '14 at 05:19
  • There are several ways of doing this. You can do the following if you don't want to use $_GET variable $urlArray = explode('&', $user['page']); foreach($urlArray as $queryParam) { $unitQueryParam = explode('=', $queryParam); print $unitQueryParam[1]; } – Safique Ahmed Faruque Dec 10 '14 at 05:23