R
R
romaro2021-12-05 22:26:34
Regular Expressions
romaro, 2021-12-05 22:26:34

How to drop a domain using a regular expression?

Does anyone have a working regex that can get the address of a resource without taking into account the domain part? For example, if all of the lines below would return '/test-url':

https://www.domain.ru/test-url
http://www.domain.ru/test-url
https://domain.ru/test-url
http://domain.ru/test-url
https://localhost/test-url
http://localhost/test-url

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Taran, 2021-12-06
@romaro

https://regex101.com/r/7TW7vc/1

S
Slava Rozhnev, 2021-12-06
@rozhnev

Regular Expression:
/\/([^\/]+)$/
But it's better to use built-in language functions (PHP has parse_url function for example):

<?php
$url = 'https://www.domain.ru/test-url';

// using preg_match
preg_match('/(\/[^\/]+)$/', $url, $matches);

echo $matches[1].PHP_EOL;


// using parse_url 
echo parse_url($url, PHP_URL_PATH);

PHP parse_url

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question