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
https://forums.phpfreaks.com/topic/52676-help-on-preg_replace_callback/
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'];
}

?>

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.