There is a url with the following address site.ru/content/grazhdanskie-spory?clear_cache=Y .

I need to get

 site.ru/content/grazhdanskie-spory/grazhdanskie-spory 

I try

 $url = preg_replace("#^/content/([a-zA-Z-])+#",$1","site.ru/content/grazhdanskie-spory?clear_cache=Y"); 

but it’s not how to fix it?

    2 answers 2

    The best solution, in your case, is Dmitry's solution, but you can also use the built-in parse_url function for such purposes, which parses the URL in parts and puts the results into an array.

     $link = 'http://site.ru/content/grazhdanskie-spory?clear_cache=Y'; if ($url = parse_url($link)) { printf('%s://%s%s', $url['scheme'], $url['host'], $url['path']); } 

    Below you asked the question that you want to get the end point of the path in the URL.

    I suggest 2 options for solving this problem:

    1: parse_url

     $url = 'http://site.ru/content/grazhdanskie-spory?clear_cache=Y'; $url_path = parse_url($url, PHP_URL_PATH); $parts = explode('/', $url_path); $last = end($parts); echo $last; 

    2: basename

     $url = "http://site.ru/content/grazhdanskie-spory?clear_cache=Y"; $lastPath = preg_replace("/\?.*/", "", basename($url)); 

    basename will return the endpoint of the path in the URL, but it will be: grazhdanskie-spory? clear_cache = Y in this case, so it needs to be truncated using a regular expression.

    • Please tell me how to get such a solution, let's say there is such a link site.ru/content/grazhdanskie-spory/text1/....../textN?clear_cache=Y How to get the value of textN? Well, t .e no matter how long the link will be, the main thing is to get the value between? and last / - ChromeChrome
    • Updated the answer :) - Firepro

    This is what you need

     preg_replace("/\?.*/", "$1/grazhdanskie-spory", "site.ru/content/grazhdanskie-spory?clear_cache=Y"); // site.ru/content/grazhdanskie-spory/grazhdanskie-spory 
    • Change the second parameter "$ 1 / grazhdanskie-spory" to '', then the design will become universal and help trim any request parameters, and also will not add "grazhdanskie-spory", which is not needed at all) - Firepro
    • I think the answer should be preg_replace("/\?.*/", "/grazhdanskie-spory", "site.ru/content/grazhdanskie-spory?clear_cache=Y"); . The template is not exciting submasks, so $1 not needed. - Wiktor Stribiżew
    • Wiktor, here as a whole the second parameter should be empty, the output of your site.ru/content/grazhdanskie-spory/grazhdanskie-spory function, I think grazhdanskie-spory duplication is not required. - Firepro
    • @Firepro: I need to get site.ru/content/grazhdanskie-spory/grazhdanskie-spory - Wiktor Stribiżew