PHP, Remove Parts of a URL Variable

I have the following php variable

$currentUrl 

This php variable returns me the current page of the url. For example: it returns:

 http://example.com/test-category/page.html?_ore=norn&___frore=norian 

What php code I can use, it will take this URL link and delete everything after " .html " and return me a link to a clean URL, for example:

 http://example.com/test-category/page.html 

This will be returned in the new variable $ clean_currentUrl

+4
source share
3 answers

Something like that:

 <?php $currentUrl = 'http://example.com/test-category/page.html?_ore=norn&___frore=norian'; preg_match('~http:\/\/.*\.html~', $currentUrl, $matches); print_r($matches); 

See amigura comment below. To handle this case, modify the regex:

 <?php $currentUrl = 'http://example.com/test-category/page.html?_ore=norn&___frore=norian'; preg_match('~(http:\/\/.*\..+)\?~', $currentUrl, $matches); print_r($matches); 
+1
source

With PHP parse_url ()

 <?php $url = "http://example.com/test-category/page.html?_ore=norn&___frore=norian"; $url = parse_url($url); print_r($url); /* Array ( [scheme] => http [host] => example.com [path] => /test-category/page.html [query] => _ore=norn&___frore=norian ) */ ?> 

Then you can create the desired URL from the values.

 $clean_url = $url['scheme'].'://'.$url['host'].$url['path']; 
+13
source
 $parts = explode('?', $currentUrl); $url = $parts[0]; 
+1
source

Source: https://habr.com/ru/post/1487668/


All Articles