简体   繁体   中英

Using Regex lookaround to insert HTML into string in specific location

I am working with an automatically generated HTML menu (generated by WordPress) and I'm trying to use preg_replace and regex lookaround techniques to insert an HTML snippet into specific locations within the menu code.

I am very new to using regex to make matches. I tried using a combination of lookahead and lookbehind to match a specific location in the menu code and have had some trouble getting it to appear in the exact spot I want.

Here is what I have so far: https://regex101.com/r/thq6rK/1

(?=<\/li><li id=.*?mega-menu )

The HTML menu code is in the example regex101 editor and if I'm correct, there should only be one match (even though there are two instances of class="mega-menu" being used in the HTML.

I'm trying to locate the spot right before the each instance of <li>'s with the class "mega-menu" and insert a custom <div class="custom-class"></div> directly before the preceding closed .

I am sorry, it's a bit hard to explain. Here is an example.

The chunk I'm interested in:

</li></ul></li></ul></li><li id="menu-item-26880" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children mega-menu has-picture has-picture-2 menu-item-26880 nav-item">

How I want to work (the line breaks are just to better show the inserted <div> ):

</li></ul></li></ul>
<div class="custom-class">This would be inserted</div>
</li><li id="menu-item-26880" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children mega-menu has-picture has-picture-2 menu-item-26880 nav-item">

Thank you for any help you may be able to give me.

You're close. Change .*? to [^>]* so it won't match across multiple elements.

You think that using a non-greedy regexp should make it find the shortest match. But greediness only applies on the right, not the left. * starts matching as soon as it can; when it's greedy, it matches the longest repetition that's consistent with the rest of the pattern, when it's non-greedy it matches the shortest repetition.

https://regex101.com/r/thq6rK/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM