Replacing values using preg_replace
Posted
by Jeepstone
on Stack Overflow
See other posts from Stack Overflow
or by Jeepstone
Published on 2010-05-13T15:27:45Z
Indexed on
2010/05/13
15:44 UTC
Read the original article
Hit count: 328
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;
}
© Stack Overflow or respective owner