regex - How can I replace the Nth instance of a string in PHP? -
i need dynamically add active class shortcode in wordpress based on active number set in it's parent shortcode.
the parent looks this:
$active = 3; $output .= "\n\t\t".wpb_js_remove_wpautop($content); the $content variable can technically consist of in between shortcodes tags, specifically, should include more child shortcodes (it's tabs shortcode parent tabs , children tab).
what need parse $content , replace nth ($active variable) instance of [vc_tab [vc_tab active="true"
i realize there better ways design shortcode compensate limited in can because modifying visual composer use bootstrap tabs instead of jquery , bootstrap tabs need active class on both <li> , <div class="tab-pane"> elements don't want users have add active number parent shortcode , active true/false child confusing.
so far googling can find replacing first occurrence or occurrences, not nth one.
temporarily using jquery make appropriate <div> active results in undesirable fouc there no pane visible on load , 1 pops place when jquery runs.
$('.tabs-wrap').each(function(){ var activetab = $(this).find('.tabbed li.active a').attr('href'); $(this).find(activetab).addclass('active'); });
this interesting problem, , got me thinking if need regex this.
my conclusion don't believe do. need find occurrence of nth $needle, , replace replacement. can achieved through simple string manipulation, follows:
define variables. input string,
$activeindex,$needlelooking for, ,$replacement replacenthmatch with.$string = "[vc_tab [vc_tab [vc_tab [vc_tab [vc_tab [vc_tab"; $active = 3; $needle = "[vc_tab"; $replace = '[vc_tab active="true"';now, need make sure there enough
$needles in$string, otherwise can't replacement.if( substr_count( $string, $needle) < $active) { throw new exception("there aren't enough needles in string replacement"); }now, know can replacement. let's find
$indexin stringnthoccurrence of$needleends:$count = 0; $index = 0; while( $count++ < $active) { $index = strpos( $string, $needle, $index) + strlen( $needle); }now,
$indexpointing here in string:[vc_tab [vc_tab [vc_tab [vc_tab [vc_tab [vc_tab ^ herewe can simple
substr()'s form final string:$result = substr( $string, 0, $index - strlen( $needle)) . $replace . substr( $string, $index); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ before nth match after nth matchso, end concatenating:
[vc_tab [vc_tab[vc_tab active="true"[vc_tab [vc_tab [vc_tab
this results in our final output:
[vc_tab [vc_tab [vc_tab active="true" [vc_tab [vc_tab [vc_tab try out in the demo!
Comments
Post a Comment