How do I get only what is after ? and before & ?
$url = "https://www.dominio.com/login?erro=1&data=2018-03-06";
$url_cod = explode('?', $url);
There he is returning everything that comes after the question mark.
How do I get only what is after ? and before & ?
$url = "https://www.dominio.com/login?erro=1&data=2018-03-06";
$url_cod = explode('?', $url);
There he is returning everything that comes after the question mark.
If you want to get the parameters passed by GET from any URL - not necessarily from the current page, which PHP already makes available in $_GET
- there are functions that are suitable for this:
parse_url
gets a URL and returns array with the main components - including the querystring, which is what matters here.
parse_str
is done to break array querystrings
Putting the two together:
$url = "https://www.dominio.com/login?erro=1&data=2018-03-06";
$partes = parse_url($url);
if(!empty($partes['query'])) {
$vars = [];
parse_str($partes['query'], $vars);
var_dump($vars);
}
// Saída:
//
// array(2) {
// ["erro"]=>
// string(1) "1"
// ["data"]=>
// string(10) "2018-03-06"
// }
About the approach you were trying:
How do I get only what's after? and before &?
Thinking about this problem in a generic way (because to treat URLs I would use the above code), it is simple to solve with string manipulation. With explode
you have already managed to get a string like this:
$sua_string = "erro=1&data=2018-03-06";
Looking at this, just find the first &
and get everything that is before it:
$sua_string = "erro=1&data=2018-03-06";
$pos = strpos($sua_string, '&');
$resultado = substr($sua_string, 0, $pos-1);
echo $resultado; // erro=1
Everything that comes after ?
is populated by global super $_GET
, so if you want to get some parameter in the url you can do the following:
$data = $_GET['data'];
This code would return the value '2018-03-06'
.
To get the error just do:
$erro = $_GET['erro'];
This code would return the value 1
.
As you want the value with the name of the variable, you can concatenate the value with a string.
$erroString = 'erro='.$erro;
The explode will transform $ url_cod into an array, to get what is before just put:
$parte_url = $url_cod[1];
//Ou [0] para oque vem antes
For the '&' you use the same system
Or if you want to get the GET parameters, do as @Phelipe answered above
$url = "www.google.com?&nome_da_variavel_recebida=123";
$valor = $_GET['nome_da_variavel_recebida'];
//Nesse caso $valor seria igual a 123