Adam
Adam

Reputation: 1299

Convert regex string to URL

Im trying to convert words into URLs. the words are separated with a comma ,. But my problem is that the first word is not taken into account, because there is no comma infort of it.

public static function convertHashtags($str){
        $regex = "/,+([a-zA-Z0-9_]+)/";
        $str = preg_replace($regex, '<a href="'.Config::get('URL').'index/hashtag/$1">$0</a>', htmlentities($str));
        return($str);
    }

For example $str=june,mars,april results that only mars and april get URLed, not june.

Upvotes: 1

Views: 394

Answers (1)

anubhava
anubhava

Reputation: 785156

You can change your regex to:

$regex = '/(?<=,|^)([a-zA-Z0-9_]+)/';

to match line start or comma before your words.

You can shorten your regex to:

$regex = '/(?<=,|^)(\w+)/';

Upvotes: 1

Related Questions