Jump to content

Help on preg_replace_callback()


grethe

Recommended Posts

Hi i need help on the function preg_replace_callback(). I always get this error:

 

Warning: preg_replace_callback() [function.preg-replace-callback]: Requires argument 2, 'make_br', to be a valid callback

 

Here is my code:

$text = preg_replace_callback('/(\<p\>)(.+)(\<\/p\>)/sU', 'make_br', $text);
function make_br($matches) {
  $matches['2'] = trim($matches['2']);
  $matches['2'] = preg_replace('/\n/', "<br/>\n", $matches['2']);
  return $matches['2'];
}

 

What am i doing wrong?

Link to comment
Share on other sites

Yes you're right it works fine if i isolate it. Thanks.

I've also figured out how to make i work, but there's something in PHP i don't understand then. Can't a function be created anywhere - like in a function and stille work everywhere?

 

This works:

<?php

$text = "123";

echo interpret($text);

function interpret($text) {
  $text = preg_replace_callback('/(\<p\>)(.+)(\<\/p\>)/sU', 'make_br', $text);
  function make_br($matches) {
    $matches['2'] = trim($matches['2']);
    $matches['2'] = preg_replace('/\n/', "<br/>\n", $matches['2']);
    return $matches['2'];
  }

  return $text;
}

?>

 

This doesn't work:

<?php

$text = "123";

echo interpret($text);

function interpret($text) {
  $text = preg_replace_callback('/(\<p\>)(.+)(\<\/p\>)/sU', 'make_br', $text);

  return $text;
}

function make_br($matches) {
  $matches['2'] = trim($matches['2']);
  $matches['2'] = preg_replace('/\n/', "<br/>\n", $matches['2']);
  return $matches['2'];
}

?>

Link to comment
Share on other sites

It was the first one that didn't work for me.  The second one did.  However, the first one did work when I moved the inner function definintion above the preg_replace_callback that called it.  PHP functions are supposed to be able to be referenced before their definition but maybe that doesn't apply to functions defined within functions.

Link to comment
Share on other sites

Whoops.. yes you are right. I mixed them. Hmm.. but still that explanation i think is weird, why shouldn't they work like everywhere else. But maybe you are right. Does annyone know why the function behaves like this?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.