1

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.

1 Answer 1

1

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+)/';
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer! but the URL looks like this now: index/hashtag/, its a comma instead of the word. And i made a mistake in my first post. There is no space between words. june,mars,april
The m flag is useless in this example. It is used to tell . to also match newlines. Since you aren't using ., you can remove it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.