Search code examples
phpregexpreg-replacestrpos

Replace http and https..?


I have a simple php and jquery chatroom for my users. I am currently replacing the www. and http:// strings with a linked url version of them to make links clickable. This works awesome, but does not catch https:// links. What do I change to make it do http or https? Here is the current code

$find = 'http://';
$check_for_links = strpos($message, $find);
if($check_for_links === false) {
    $message = preg_replace('/((www)[^ ]+)/', '<a href="http://$1">$1</a> ', $message);
} else {
    $message = preg_replace('/((http:\/\/)[^ ]+)/', '<a href="$1">$1</a> ', $message);
}

Solution

  • Use preg_match function instead of strpos to "catch" both http and https scheme:

    if (!preg_match("/https?:/", $message)) {
        $message = preg_replace('/((www)[^ ]+)/', '<a href="http://$1">$1</a> ', $message);
    } else {
        $message = preg_replace('/((https?:\/\/)[^ ]+)/', '<a href="$1">$1</a> ', $message);
    }