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
x
function replaceContent($content,$mysqli){
$search = "/([)(.*?)(])/";
$newContent = preg_replace($search,makeUrl('$2',$mysqli),$content);
return $newContent;
}
in that function I have a function called makeUrl:
JavaScript
function makeUrl($id,$mysqli){
$query = "SELECT url FROM pages WHERE id = '".$id."' ";
$result = $mysqli->query($query);
$data = $result -> fetch_assoc();
return $data['url'];
}
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
preg_replace_callback($search, function($match) use($mysqli) {
return makeUrl($match[2], $mysqli)
}, $content)