Zac
Zac

Reputation: 12856

Regex help grabbing values from urls

I am struggling with creating a regular expression to print the part of the url that I want. With PHP I am grabbing the path after the primary domain name. They look something like :

this-link-1
this-is-another-one-3

The php I am using to grab these is like :

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$whereami =  parse_url($url, PHP_URL_PATH);
echo $whereami;

Can someone help me write a regular expression to always remove the -# for the whereami variable ? So from this example $whereami would be this-link and this-is-another-one after run through the expression

Upvotes: 1

Views: 61

Answers (2)

Glass Robot
Glass Robot

Reputation: 2446

You can also do it without regex:

echo implode('-', explode('-', 'this-link-1', -1));

Result:

this-link

Upvotes: 1

Dogbert
Dogbert

Reputation: 222438

preg_replace("/-\d+$/", "", $whereami)

Example:

echo preg_replace("/-\d+$/", "", "this-is-another-one-3");

Output:

this-is-another-one

Upvotes: 4

Related Questions