phpstringstripos

String search function to return boolean if needle is found in haystack


I'm writing a simple function which will convert string containing url into a clickable link. Convertion itself is simple but part of basic validation if a string contains one of protocol prefixes seems to be surprisingly difficult.

Currently my code looks like this:

<?php

function link2code($link) {
    if (stripos($link, 'http://' or 'https://' or 'ftp://' or 'ftps://') === true) {
        return "<a href=\"$link\">$link</a>";
    } else {
        echo('Please provide whole link with protocol part, for example: http://myawesomewebsite.com');
    }
}

echo link2code("http://127.0.0.1");

As you can see i want to return boolean value telling if needle is in haystack. How can i achieve it?


Solution

  • You can use preg_match for that:

    if(preg_match("~^(ht|f)tps?://~i", $link)) { //...etc