0

Can someone please help me build regex to make sure that a string starts with one of the following?

https://www.youtube.com
https://www.youtube.be
http://www.youtube.com
http://www.youtube.be
https://youtube.com
https://youtube.be
http://youtube.com
http://youtube.be
www.youtube.com
www.youtube.be
youtube.com
youtube.be

I am working in on PHP system that allows people to add a YouTube video to a web page, I only need to make sure that the link users add begins appropriately and is also a valid URL. That should be then be safe enough for the string to be stored after the user has entered it and also embedded as a YouTube video when viewed later.

1
  • regexr.com is a very well made site to learn regex and try out this kind of things Commented Jul 31, 2016 at 13:35

2 Answers 2

1

That's as simple as

^(https?:\/\/)?(www\.)?youtube\.(be|com)

Little bit of explanation:

  • ^ - start of the string
  • https? - http with optional s
  • :\/\/ - ://
  • (www\.)? - optional www.
  • youtube\. - youtube.
  • (be|com) - be or com

If you also want to match youtu.be, use this:

^(https?:\/\/)?(www\.)?(youtube\.(be|com)|youtu\.be)
Sign up to request clarification or add additional context in comments.

4 Comments

Does that check for http and https?
Thanks. Will test later when back on the job and report back.
@Peter added explanation in case you don't understand something immediately.
That's perfect, thanks for your answer and the additional explanation.
0
((?:https?:\/\/)?(?:www.)?youtu(?:\.?be)?\.(?:com|be))

Includes:

https://www.youtube.com
https://www.youtube.be
http://www.youtube.com
http://www.youtube.be
https://youtube.com
https://youtube.be
http://youtube.com
http://youtube.be
www.youtube.com
www.youtube.be
youtube.com
youtube.be
youtu.be
www.youtu.be
http://www.youtu.be
https://www.youtu.be
http://youtu.be
https://youtu.be

PHP:

$re = "/((?:https?:\\/\\/)?(?:www.)?youtu(?:\\.?be)?\\.(?:com|be))/"; 
$str = "https://www.youtube.com\nhttps://www.youtube.be\nhttp://www.youtube.com\nhttp://www.youtube.be\nhttps://youtube.com\nhttps://youtube.be\nhttp://youtube.com\nhttp://youtube.be\nwww.youtube.com\nwww.youtube.be\nyoutube.com\nyoutube.be\nyoutu.be\nwww.youtu.be\nhttp://www.youtu.be\nhttps://www.youtu.be\nhttp://youtu.be\nhttps://youtu.be\n\n\nbsadf.fds\n\nyoutube\.(be|com)"; 

preg_match_all($re, $str, $matches);

UPD: Yes, @nicael is right, but I would change so:

((?:https?:\/\/)?(?:www\.)?(?:youtube\.(?:be|com)|youtu\.be))

1 Comment

OP didn't really ask for youtu.be. Although, you've implemented it incorrectly anyway. Matches youtu.com, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.