Regex Substitution to add a class to a specific html tag

55 Views Asked by At

I need to do a regex find-replace on the post content of a wordpress site in order to change all existing <h4> tags to <h2> tags. I then need to style the <h4> tags to look like <h2> tags.

My plan was to add a class to the new <h2> tags...

<h4> Some poorly written html </h4> becomes <h2 class="pseudo-h4"> Some poorly written html </h2>

I feel like this should be doable with regex, but I just cannot seem to grok the more advanced parts of regex. My current working approach is to use this regex (?<=h4)(.+class=") to capture the 'class=' part of any h4 opening tag and then use $1pseudo-h4 as the substitution string. Once that is done I can go back and replace all h4s without regex because those which are "pseudo-h4s" will already be marked by the class.

I have a few problems...

1 - wp-cli is hanging when I try to run this on wp_posts. Maybe this is normal?
2 - $1pseudo-h4 with a space on the end is needed prevent my class from concatenating with the next class, but when i pass the argument with a space on the end i get "unknown --regex  parameter"
3 - In my tester it worked, but I dont actually know why this pattern wont match the tag of a previous element, for instance...

<h4>Sup<h4><p class="extra-cheese">Bla bla<p> my lookbehind should see the <h4> and .+ should go through as many characters as it needs to hit the "class=" section right?

0

There are 0 best solutions below