Jump to content

Regular expression question


jumpenjuhosaphat

Recommended Posts

Okay, I am trying to figure out the regex's so I can form my own.  I am currently trying to build a regex that will validate a URL.  The url can be:

http://www.domain.com

http://domain.com

http://www.domain.com/

http://domain.com/

http://sub.domain.com

 

or without the http, or with https, and accepting any TLD.

 

I need to strip anything after the TLD, so if there are 3 "/"'s, then anything after the third "/" will need to be removed.  Also, if the http(s) part isn't included, I would like to add it in.

 

Here is what I've come up with so far:

 

((http | https):\/\/){1}([a-zA-Z0-9]\.)*([a-zA-Z]+\/?)$

 

Is that even close?  Any help is appreciated, please. :)

Link to comment
Share on other sites

Some related topics:

 

http://www.phpfreaks.com/forums/index.php/topic,123121.0.html

http://www.phpfreaks.com/forums/index.php/topic,96937.0.html

 

<pre>
<?php
$tests = array(
	'http://www.domain.com',
	'http://domain.com',
	'http://www.domain.com/',
	'http://domain.com/',
	'http://sub.domain.com'
);
foreach ($tests as $test) {
	echo $test, ' => ';
	echo preg_match('%
		^(?:https?|ftp)://
		(?:[a-zA-Z0-9]+\.)+
		[a-zA-Z0-9]+/?
		\z
	%x', $test);
	echo '<br>';
}
?>
</pre>

Link to comment
Share on other sites

Okay, so I found a function called parse_url, that someone pointed out should work for what I need.

 

Here is how I used it:

  elseif($type=="url")
    {
    if(!preg_match("/^http(s)?/si", $var))
     {
     $var = "http://" . trim($var);
     }
     $var = parse_url( $var );
     $var=$var['scheme'] . "://" . $var['host'];
    }

 

What you don't see in this code is that I trimmed the $var variable and stripped slashes, and added slashes and stripped tags.  SHould this work for what I need it for?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.