Skip to content
● Grav 2.2 is out: 2x faster cold starts and 96% less memory on big sites. Read the announcement →

[SOLVED] Define a callback function in a plugin

Solved by Anna View solution

Started by Anna 8 years ago · 1 replies · 852 views
8 years ago

I'm writing a little plugin that checks pages for plain text email addresses and turns them into javascript-encrypted mailto links. I have defined a function munge($address) and I'm using it with preg_replace_callback like this:

PHP
public function onPageContentRaw(Event $e)
{
    // Get the current raw content
    $content = $e['page']->getRawContent();

    // find plain text email addresses and replace them with munge() results
    $content = preg_replace_callback('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/', 'munge', $content);
}

However, I get a Crikey! error saying "preg_replace_callback(): Requires argument 2, 'munge', to be a valid callback". So how do I define the munge function correctly?

Thanks for your time!


Side note: I do know that this regex will not catch all valid email addresses. This is not a problem since I know when people putting content into Grav sites that I have set up have whack email addresses – if this ever happens I will fix the regex.

8 years ago Solution

I got it to work! In case somebody else needs it, this is my solution:

PHP
$content = preg_replace_callback('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/', array(get_class($this), 'munge'), $content);

(Stackoverflow tipped me off.)

Suggested topics

Topic Participants Replies Views Activity
Plugins · by renedebaaij, 12 hours ago
0 16 12 hours ago
Plugins · by complanar, 2 weeks ago
6 379 2 weeks ago
Plugins · by BenLaKnet, 2 weeks ago
1 197 2 weeks ago
Plugins · by complanar, 1 month ago
2 472 4 weeks ago
Plugins · by Vladimir Novak, 2 months ago
3 750 2 months ago