-->

How to call a function within preg_replace()?

2019-09-16 15:35发布

问题:

I've written a function that replaces certain patterns in a blog. For example when someone types: :) this function replaces it with a smiley emoticon.

However now I'm trying to do something special, but don't know how to accomplish it. I would like to parse a match to another function like so:

$pattern[] = "/\[ourl\](.*?)\[\/ourl\]/i";
$replace[] = "" . getOpenGraph("$1") . "";
$value = preg_replace($pattern, $replace, $value);

If someone uses [ourl]www.cnn.com[/ourl] this function will retrieve the OpenGraph information and return a specific HTML code.

However this does not work because it doesn't parse the $1 to the function.

How can I solve this?

UPDATE:

Based on the hint u_mulder gave me I was able to pull it off

回答1:

I have created a demonstration to show how to call getOpenGraph() and how the capture groups are passed as arguments without specifying them in the second parameter of preg_replace_callback().

I modified the pattern delimiters so that the slash in the end tag doesn't need to be escaped.

function getOpenGraph($matches){
    return strrev($matches[1]);  // just reverse the string for effect
}

$input='Leading text [ourl]This is ourl-wrapped text[/ourl] trailing text';
$pattern='~\[ourl\](.*?)\[/ourl\]~i';
$output=preg_replace_callback($pattern,'getOpenGraph',$input);   
echo $output;

Output:

Leading text txet depparw-lruo si sihT trailing text


回答2:

Try this:

<?php

$content = "[ourl]test[/ourl]\n[link]www.example.com[/link]";
$regex = "/\[(.*)\](.*?)\[(\/.*)\]/i";

$result = preg_replace_callback($regex, function($match) {
    return getOpenGraph($match[1], $match[2]);
}, $content);

function getOpenGraph($tag, $value) {
    return "$tag = $value";
}
echo $result;