Replacing values using preg_replace
- by Jeepstone
I have a Joomla plugin (not important in this context), which is designed to take an input with a load of numbers (within a paragraph of text) and replace them with a series of s.
My problem is that I need to do a preg_replace on my $article-text, but I don't know how to then apply the changes to the matched terms. I've seen the preg_replace_callback, but I don't know how I can call that within a function.
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;
}
AMENDED CODE:
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;
}