Skip to content
Advertisement

Preg_replace content with mysql query

I’m creating a replacement function. I have data in a db with a field ‘content’ that returns the content for a page. In that content I have a url tag like <a href="[2]">title</a>. The number between the [brackets] is the page_id of my pages table.

I have a function called replaceContent:

JavaScript

in that function I have a function called makeUrl:

JavaScript

What I tried:

  • When I call the function makeUrl(2,$mysqli) standalone, it works fine and returns the url.
  • When I change the return in the makeUrl function with ‘abc $id’ the replaceContent function replaces the url with ‘abc 2’

But together I get a blank return…

Anybody knows what I’m doing wrong? Thanks a lot

Advertisement

Answer

Group references (e.g. $2) are parsed in any replacement strings, but you’re replacing with the return value of a function. So you’re litereally passing along $2 as the argument, not 2.

Instead, feed the matches to a callback.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement