How to handle unclosed tags in image captions

Is there any way to “clean” the output of an image caption? We have a site that uses an ACF gallery field that’s output via the L&L slider. If an editor adds a html tag to the image (eg: as a creative commons reference etc…) but fails to properly close it, it causes problems for the rest of the page.

Obviously in an ideal world there wouldn’t be errors, but a typo meant they used <a> instead of </a> to close it so we just want to try and add in a layer of protection against future errors.

This it the code we’re using

  <Loop acf_gallery=stadium_images>
      <div class="image_slide">
        <img src="{Field url}" alt="{Field alt}">
        <div class="image_text">
          <Field alt />
          <If field=caption exists>
            <em><Field caption  /></em>

The browser itself often corrects such malformed HTML in certain situations, like automatically closing unclosed tags. You might be able to achieve it by replacing this:

<em><Field caption /></em>


<div style="font-style: italic">
  <Field caption />

The closing div might help let the browser know that any unclosed tags within should be closed.

Also, the em tag may be problematic depending on what’s inside of it, for example another div.

Thanks Eliot - wouldn’t the closing image_text div have the same affect though? Ie: the output is already within a div that gets closed within the loop output.

They shouldn’t be putting divs in the captions, but you never know so point taken on that as well.