Martin AJ
Martin AJ

Reputation: 6697

How to match the last segment of the URL (string)?

I want to add/replace the last segment of the url (regardless url parameters) with en.


Here is four examples:

One:

$str = 'http://localhost:8000/search/fa?q=sth';

expected output:

//=>    http://localhost:8000/search/en?q=sth

Two:

$str = 'http://localhost:8000/search?q=sth';

expected output:

//=>    http://localhost:8000/search/en?q=sth

Three:

$str = 'http://localhost:8000/search';

expected output:

//=>    http://localhost:8000/search/en

Four:

$str = 'http://localhost:8000/search/fa';

expected output:

//=>    http://localhost:8000/search/en

Also here is what I've tried so far:

/\/(?:en|fa)(?=\??)/

php version:

preg_replace('/\/(?:en|fa)(?=\??)/', '/en', Request::fullUrl())

As you see, my pattern depends on en, fa keywords and it fails when there isn't none of them.

Upvotes: 1

Views: 90

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

Split url to individual components with parse-url, manipulate path, and compile it back:

$str = 'http://localhost:8000/search/fa?q=sth';

$parts = parse_url($str);

//play with the last part of the path:
$path = explode('/', $parts['path']);
$last = array_pop($path);
if (!in_array($last, ['en','fa'])) {        
    $path[] = $last;
}
$path[]='en';

//compile url
$result = "";
if (!empty($parts['scheme'])) {
    $result .= $parts['scheme'] . "://";
}
if (!empty($parts['host'])) {
    $result .= $parts['host'];
}
if (!empty($parts['port'])) {
    $result .= ":" . $parts['port'];
}
if (!empty($path)) {
    $result .= implode('/', $path);
}
if (!empty($parts['query'])) {
    $result .= '?' . $parts['query'];
}

echo $result;

Example

Upvotes: 1

Related Questions