skip to Main Content

I need to check if a given string is valid. For me, the following and any other similar combinations are all valid URLs

'https://example.com/api/',
'https://www.example.com/test-subpath',
'https://www.example.com',
'example.com/test/page',
'www.example.com',
'www.subdomain.example.com',
'https://www.subdomain.example.com',
'subdomain.example.com',
'http://subdomain.example.com',
'https://subdomain.example.com'

while

'user-service/api/'

is invalid. I tried parse_url() and filter_var($url, FILTER_VALIDATE_URL) methods but non worked.

Thanks in advance.

2

Answers


  1. You have not described the rules of what to match and what not to match. All you have provided are some. For those examples, just searching for a dot will give you the correct answer.

    Login or Signup to reply.
  2. This is so simple example to validate your URL patterns.

    <?php
    $re = '#example[.]com#i';
    $str = 'subdomain.example.com';
    
    preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);
    
    // Print the entire match result
    var_dump($matches);
    ?>
    

    Hope this helps for you.
    Thank you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search