我试图让我的客户端通过在他们的所见即所得编辑器中插入一个简短代码来调用具有各种代码片段的函数。php替换正则表达式而不是字符串替换
例如,他们会喜欢写东西......
[getSnippet(1)]
这会打电话给我的getSnippet($ id)的PHP函数,输出相应的 '块'。
它工作时,我硬编码的$ id像这样...
echo str_replace('[getSnippet(1)]',getSnippet(1),$rowPage['sidebar_details']);
可是,我真的想使“1”的动态。我是那种正轨的东西像...
function getSnippet($id) {
if ($id == 1) {
echo "car";
}
}
$string = "This [getSnippet(1)] is a sentence.This is the next one.";
$regex = '#([getSnippet(\w)])#';
$string = preg_replace($regex, '. \1', $string);
//If you want to capture more than just periods, you can do:
echo preg_replace('#(\.|,|\?|!)(\w)#', '\1 \2', $string);
不太工作:(
什么不适用于您的代码? – hakre
看看'preg_replace_callback()'。它允许您提供一个函数,该函数接收由正则表达式匹配的字符串的位,并返回替换。 – Barmar