tags:

views:

52

answers:

3

I have some code like this (this is a simplified example):

function callback_func($matches) {
  return $matches[0] . "some other stuff";
}

function other_func($text) {
  $out = "<li>"; 
  preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);
  $out .= $desc ."</li> \r\n";
  return $out;
}

echo other_func("This is a _test");

The output of this should be

<li>This is a _testsome other stuff</li>

but I just get

<li>This is a _test</li>

What am I doing wrong/what bizarre incantation is required to appease the php gods?

A: 

The problem is that you're never appending the output from the function into the $out variable. So in callback_func() you have to use:

$out .= $matches[0] . "some other stuff";

Then it will add the result into the string for you to output. As it is, you're just returning a value and doing nothing with it.

BraedenP
You're mixing scopes. `$out` is in `other_func` but `$matches` is in `callback_func`.
Ben Blank
+5  A: 

preg_replace_callback does not modify the string in place, but instead returns a modified copy of it. Try the following instread:

function other_func($text) {
    $out = "<li>"; 
    $out .= preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);
    $out .= "</li> \r\n";
    return $out;
}
Ben Blank
Oops, should have refreshed. Figured it out just after you did. Thanks anyway.
Paul Wicks
A: 

Figured it out. preg_replace_callback doesn't modify the original subject, which I assumed it did. I had to change

preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);

to

$desc = preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);
Paul Wicks