title: How can I replace the Nth instance of a string in PHP?
body: <p>I need to dynamically add an active class to a shortcode in wordpress based on the active number set in it's parent shortcode. </p>
  
  <p>The parent looks like this: </p>
  
  <pre><code>$active = 3;
  $output .= "\n\t\t".wpb_js_remove_wpautop($content);
  </code></pre>
  
  <p>The $content variable can technically consist of anything in between the shortcodes tags, but specifically, should include more child shortcodes (it's a tabs shortcode so the parent is tabs and the children are tab). </p>
  
  <p>What I need to do is parse <code>$content</code> and replace the Nth (<code>$active</code> variable) instance of <code>[vc_tab</code> with <code>[vc_tab active="true"</code></p>
  
  <p>I realize there are better ways to design the shortcode to compensate for this but I am limited in what I can do because I am modifying Visual Composer to use Bootstrap tabs instead of jQuery and Bootstrap tabs need the active class on both the <code>&lt;li&gt;</code> and the <code>&lt;div class="tab-pane"&gt;</code> elements but I don't want the users to have to add an active number to the parent shortcode and an active true/false to the child as that will get confusing. </p>
  
  <p>So far from googling I can only find replacing the first occurrence or all occurrences, not the Nth one. </p>
  
  <p>Temporarily I am using jQuery to make the appropriate <code>&lt;div&gt;</code> active but it results in an undesirable FOUC where there is no pane visible on load and then one pops into place when the jQuery runs. </p>
  
  <pre><code>$('.tabs-wrap').each(function(){
    var activeTab = $(this).find('.tabbed li.active a').attr('href');
    $(this).find(activeTab).addClass('active');
  });  
  </code></pre>