0

I am generating a set of div having the same class name. I'm trying to replace the class name of the second div only.

I have used preg_replace but it is replacing all div tags with the bar class name instead of only the class name of the second div, as seen below.

function add_menuclass($mynewclass) {
    return preg_replace('/<div /', '<div class="bar"', mynewclass);
}

I have:

  <div class="bar"></div>
  <div class="bar"></div>
  <div class="bar"></div>
  <div class="bar"></div>

I want:

  <div class="bar"></div>
  <div class="foo"></div>
  <div class="bar"></div>
  <div class="bar"></div>

1 Answers1

0

I solved part of the problem by doing (for WP):

function replace_class($content){
    $html = str_get_html($content);
    $html -> find('div.bar', 1) -> class = 'foo';
    return $html;
}
add_filter('wp_nav_menu', 'replace_class');