zac
zac

Reputation: 4898

Get the last 3 words from url path

url like this:

http://localhost/333/ed/a3

I tried like this

$pattern = '/(([^ ]*)\s+([^ ]*)\s+([^ ]*))$/';
preg_match($pattern, $_SERVER['REQUEST_URI'], $matches);
$last_word = $matches[0];

I get error Undefined offset: 0

Upvotes: 0

Views: 90

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

Your current error seems to happening because there is no zeroth match in the array. This is because your pattern is not matching the URL. The biggest problem I see is that your pattern insists on matching some whitespace inside the URL, which (should) never happen.

Try this version:

$pattern = '/[^\/]+\/[^\/]+\/[^\/]+$/';
preg_match($pattern, "http://localhost/333/ed/a3", $matches);
$last_word = $matches[0];
print_r(preg_split("/\//", $last_word));

Array
(
    [0] => 333
    [1] => ed
    [2] => a3
)

Demo

Upvotes: 1

Richard Tyler Miles
Richard Tyler Miles

Reputation: 685

does it have to be a regex? If so I recommend using https://regexr.com

For simplicity, I'll show how to use the built in explode function with the array slice function.

http://php.net/manual/en/function.explode.php array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

http://php.net/manual/en/function.array-slice.php array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] )

Untested Example:

$url = explode ( '\' , $_SERVER['REQUEST_URI'] ); $last_three = array_slice ( $url, -3, 3 );

Upvotes: 1

Related Questions