How to call a function within preg_replace()?

倖福魔咒の 提交于 2019-12-12 04:14:48

问题


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;


来源:https://stackoverflow.com/questions/45554259/how-to-call-a-function-within-preg-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!