Search code examples
phpregexpreg-replacepreg-replace-callback

preg replace_callback mentions and hashtags in post


Lets say i have a text,

$text = '@stackguy @flowguy I need to learn more advanced php #ilovephp';

I want to replace both @stackguyand @flowguy with those 2 anchor tags respectively. This should also work for any number of @'s in the text string.

<a href="url/stackguy">@stackguy</a>
<a href="url/flowguy">@flowguy</a>

I also want to replace #ilovephp with

<a href="search/ilovephp">#ilovephp</a>

It should also work for multi #'s. I'm guessing it'll be something like

preg_replace_callback('regex',
            create_function('$matches', '
                switch ($matches[1]) {
                    case "@":
                        return "<a href=url.$matches[2]'/'>" . $matches[2] . "</a>";
                    case "#":
                        return "<a>" . $matches[2] . "</a>";
                }
        '), $var);

What's the regex going to look like? Is my function going to match all what's needed or do i need to add a foreach loop? Thanks.


Solution

  • If you just wan't to match text preceded by @ or # use this: /([@#])(\S+)/

    View this demo: http://regex101.com/r/eP7eU0

    Note: this will match the same thing when it's inside tags. If you don't want that, you're going to need more than regex.