我有一个Joomla插件(在此上下文中并不重要),它设计用于输入一个带有数字的输入(在一段文本中)并用一系列s替换它们。
我的问题是我需要在我的$ article->文本上执行preg_replace,但我不知道如何将更改应用于匹配的术语。我见过preg_replace_callback,但我不知道如何在函数中调用它。
function onPrepareContent( &$article, &$params, $limitstart )
{
global $mainframe;
// define the regular expression
$pattern = "#{lotterynumbers}(.*?){/lotterynumbers}#s";
if(isset($article->text)){
preg_match($pattern, $article->text, $matches);
$numbers = explode("," , $matches[1]);
foreach ($numbers as $number) {
echo "<div class='number'><span>" . $number . "</span></div>";
}
}else{
$article->text = 'No numbers';
}
return true;
}
修订版代码:
function onPrepareContent( &$article, &$params, $limitstart )
{
global $mainframe;
// define the regular expression
$pattern = "#{lotterynumbers}(.*?){/lotterynumbers}#s";
if(isset($article->text)){
preg_match($pattern, $article->text, $matches);
$numbers = explode("," , $matches[1]);
foreach ($numbers as $number) {
$numberlist[] = "<div class='number'><span>" . $number . "</span></div>";
}
$numberlist = implode("", $numberlist);
$article->text = preg_replace($pattern, $numberlist, $article->text);
}else{
$article->text = 'No numbers';
}
return true;
}
答案 0 :(得分:1)
function onPrepareContent( &$article, &$params, $limitstart )
{
global $mainframe;
// define the regular expression
$pattern = "#{lotterynumbers}(.*?){/lotterynumbers}#s";
if(isset($article->text)){
$article->text=preg_replace_callback($pattern,create_function('$match','$init="<div class=\'number\'><span>";$out="</span></div>"; return $init.implode($out.$init,explode(",",$match[1])).$out;'),$article->text);
}else{
$article->text = 'No numbers';
}
return true;
}
我没有测试过,但它应该可以正常工作