Valid email/website

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Valid email/website

Post by Todd_Z »

Hey, I'm looking for a function that tells me whether something is a valid email address or a valid website address - just to give a true or false value. I'm using

Code: Select all

<?php
  $email = eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $str);
?>
for checking if its a valid email address, but what do i use for a valid website? Thanks.
Hibba
Forum Commoner
Posts: 58
Joined: Fri Oct 29, 2004 11:37 pm

Post by Hibba »

What about this:

Code: Select all

<?php 
function is_url($url) { 
    if (!preg_match('#^http\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url)) {
        return false; 
    } else { 
        return true; 
    } 
} 

if (is_url("http://www.tsn.dk")) { 
    echo "Yes, that's an URL alright"; 
} else { 
    echo "Doesn't seem to be a valid URL"; 
} 
?>
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Post by Todd_Z »

Great thank you ~ To clean up that code:

Code: Select all

<?php

function is_url($url) {
    return !preg_match('#^http\:\/\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url);
}

?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the pattern can be cleaned up a bit more...

Code: Select all

<?php

function is_url($url) {
    return !preg_match('#^http://[a-z0-9-]+\.([a-z0-9-]+\.)?[a-z]+#i', $url);
}

?>
however, that's only vaguely valid urls...
Hibba
Forum Commoner
Posts: 58
Joined: Fri Oct 29, 2004 11:37 pm

Post by Hibba »

True, if you want the action to actually see if it is a valid working URL, then you would need something like this:

Code: Select all

<?php 
function is_url($url) { 
    $fp = @fopen($url,"r"); 
    if ($fp) { 
        fclose($fp); 
        return true; 
    } else { 
        return false; 
    } 
} 
?>
Post Reply