Extract part of URL with PHP

Asked

Viewed 133 times

-1

I need to take a part of a certain URL and save in a variable but I do not know how to do with PHP, is the part that is the name of the store, there are several registered stores, so I need to get the name after the discount/ and before the last /.

https://www.localhost.com/desconto/nome-da-loja/

  • Read about the function parse_url.

  • Why don’t you pass by get? creates the link to the address " https://www.localhost.com/desconto.php?nome_loja=nome-da-loja " and then recovers using $_GET['store name']. I know it’s not the best alternative, but it might be interesting

  • I resolved with the .explode, I kept it in a variable and it worked. Thanks, guys.

1 answer

3

You can simply use regex, as long as the site URL is "fixed", doing something like:

<?php
$url = 'https://www.localhost.com/desconto/nome-da-loja/';

if (preg_match('#^https?:\/\/www\.localhost\.com\/desconto\/([^\/]+)\/#', $url, $matches)) {
    $loja = $matches[1];

    var_dump($loja);
} else {
    echo 'URL invalida';
}

Remarking, as long as the URL "is fixed" and only the store name changes.

The regex is simple, each point is necessary to escape because the . is used as a kind of wildcard

The ([^\/]+) is a group, this group takes anything that does not contain /, the sign ^ indicates that it has to be different than the one inside [...] and the sign of + at the end of the group indicates that have to take everything until the next match of the regex (the next part of the regex is \/, before the #)

The # php is used to delimit only, it has nothing to do with the regex used itself.

If you’re using with .htaccess can pick up through the REQUEST_URI, doing something like (simpler):

<?php
$url = $_SERVER['REQUEST_URI'];

if (preg_match('#^/desconto\/([^\/]+)\/#', $url, $matches)) {
    $loja = $matches[1];

    var_dump($loja);
} else {
    echo 'URL invalida';
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.