0

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?

3 Answers 3

5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oops, should have refreshed. Figured it out just after you did. Thanks anyway.
0

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.

1 Comment

You're mixing scopes. $out is in other_func but $matches is in callback_func.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.