Skip to content Skip to sidebar Skip to footer

Determine User Input Contains Url

I have a input form field which collects mixed strings. Determine if a posted string contains an URL (e.g. http://link.com, link.com, www.link.com, etc) so it can then be anchored

Solution 1:

You can use regular expressions to call a function on every match in PHP. You can for example use something like this:

<?phpfunctionmakeLink($match) {
    // Parse link.$substr = substr($match, 0, 6);
     if ($substr != 'http:/' && $substr != 'https:' && $substr != 'ftp://' && $substr != 'news:/' && $substr != 'file:/') {
        $url = 'http://' . $match;
     } else {
        $url = $match;
     }

     return'<a href="' . $url . '">' . $match . '</a>';
}
functionmakeHyperlinks($text) {
    // Find links and call the makeLink() function on them.return preg_replace('/((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/e', "makeLink('$1')", $text);
}

?>

Solution 2:

You will want to use a regular expression to match common URL patterns. PHP offers a function called preg_match that allows you to do this.

The regular expression itself could take several forms, but here is something to get you started (also maybe just Google 'URL regex':

'/^(((http|https|ftp)://)?([[a-zA-Z0-9]-.])+(.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]/+=%&_.~?-]))$/'

So your code should look something this:

$matches  = array(); // will hold the results of the regular expression match$string   = "http://www.astringwithaurl.com";
$regexUrl = '/^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$/';

preg_match($regexUrl, $string, $matches);

print_r($matches); // an array of matched patterns

From here, you just want to wrap those URL patterns in an anchor/href tag and you're done.

Solution 3:

Just how accurate do you want to be? Given just how varied URLs can be, you're going to have to draw the line somewhere. For instance. www.ca is a perfectly valid hostname and does bring up a site, but it's not something you'd EXPECT to work.

Solution 4:

You should investigate regular expressions for this.

You will build a pattern that will match the part of your string that looks like a URL and format it appropriately.

It will come out something like this (lifted this, haven't tested it);

$pattern="((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
preg_match($pattern, $input_string, $url_matches, PREG_OFFSET_CAPTURE, 3);

$url_matches will contain an array of all of the parts of the input string that matched the url pattern.

Solution 5:

You can use $_SERVER['HTTP_HOST'] to get the host information.

<?php$host = $SERVER['HTTP_HOST'];

 ?><ahref ="<?=$host?>/post.html">Post</a>

Post a Comment for "Determine User Input Contains Url"