Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Plugins

[SOLVED] Define a callback function in a plugin

Solved by Anna View solution

Started by Anna 7 years ago · 1 replies · 604 views
7 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.

7 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 Rene, 1 week ago
2 42 1 week ago
Plugins · by Xavier, 4 weeks ago
2 53 4 weeks ago
Plugins · by Luka Prinčič, 7 years ago
3 1179 1 month ago
Plugins · by Sebastian van de Meer, 1 month ago
1 47 1 month ago
Plugins · by PIERROT Alain, 2 months ago
3 71 2 months ago