Adding Zebra Stripes to a Table in a PHP String

If there is a table within a text string, such as the content area of a CMS, you may wish to apply zebra stripes to it on the server-side. A regular str_replace() can't do this because you need to replace every other occurance. Here is how to do it:

function str_replace_every_other($needle, $replace, $haystack, &$count=null, $replace_first=true) {
$count = 0;
$offset = strpos($haystack, $needle);
//If we don't replace the first, go ahead and skip it
if (!$replace_first) {
$offset += strlen($needle);
$offset = strpos($haystack, $needle, $offset);
}
while ($offset !== false) {
$haystack = substr_replace($haystack, $replace, $offset, strlen($needle));
$count++;
$offset += strlen($replace);
$offset = strpos($haystack, $needle, $offset);
if ($offset !== false) {
$offset += strlen($needle);
$offset = strpos($haystack, $needle, $offset);
}
}
return $haystack;
}

echo str_replace_every_other('<tr>', '<tr>', $modx->documentObject['content'], $count);

Src: http://xavisys.com/replace-every-other-occurrence-with-str_replace/

About Keiron

Web Developer based in the UK. Click here if you want to work with me