Danielius
Danielius

Reputation: 837

Links convertation

I have made this links converting function that puts url in <a></a>tags:

function convert_links($text) {
    $text = explode(' ',$text);
    for($i=0;$i<count($text);$i++) {
        if(filter_var($text[$i], FILTER_VALIDATE_URL))
            $text[$i] = "<a href='".$text[$i]."' target='_blank'>".$text[$i]."</a>";
        else 
            $text[$i] = $text[$i];
    }
    return implode(' ',$text);
}

I am newbie in optimization, so I want to ask: can I make this function work better/ faster? I heard that array_filter is better choice in this situation, however I can not make it work. Thanks for your help!

Now I have made one more function with array_map. so, which one is better to use?

function convert_links($text) {
    $text = explode(' ', $text);
    function convert_link($val) {
        if(filter_var($val,FILTER_VALIDATE_URL))
            return "<a href='".$val."' target='_blank'>".$val."</a>";
        else
            return $val;
    }
    $text = array_map('convert_link',$text);
    return implode(' ',$text);
}

Danielius

Upvotes: 0

Views: 39

Answers (1)

trincot
trincot

Reputation: 350841

As an alternative you could use preg_replace_callback:

function convert_links($text) {
    return preg_replace_callback("/\S+:\S+/", function ($match) {
        return filter_var($val = $match[0], FILTER_VALIDATE_URL)
            ? "<a href='$val' target='_blank'>$val</a>"
            : $val;
    }, $text);
}

Note that:

  • Instead of an if with two return statements, you can have one return and the ternary operator ? ... :.
  • In double quoted strings you can just embed your variable; no need to concatenate with ..
  • This function also works if URLs are separated by other white space than space (like newline, tab, ...).
  • The regular expression requires the word to contain at least one : not at the start or end of the word. This will avoid the more expensive filter_var calls being made on "normal" words.

Upvotes: 1

Related Questions