0

I am working on a project with facebook instant article. I would like to do automatic conversion through PHP script but I have problem with reformatting this code

[caption id="attachment_15737" align="aligncenter" width="1024"]<img class="wp-image-15737 size-full" title="bathroom counter decor" src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg" alt="bathroom counter decor" width="1024" height="768" /> © ivote[/caption]

into this code

<figure><img class="wp-image-15737 size-full" title="bathroom counter decor" src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg" alt="bathroom counter decor" width="1024" height="768" /><figcaption>© ivote</figcaption></figure>

Can anyone help me out with this problem? I would really appreciate any help. Thank you.

4
  • Which tool/language are you using here for the replacement? Commented Dec 11, 2017 at 1:58
  • I am using php script. @TimBiegeleisen Commented Dec 11, 2017 at 1:59
  • Have you tried something already? Commented Dec 11, 2017 at 2:05
  • @Adriano I have but I am not expert at Regex. I can only get <img> from the code. Commented Dec 11, 2017 at 2:10

1 Answer 1

1

You should probably consider using some sort of formal parser to handle this problem in the general case. That being said, if you are willing to accept the risks with just using a single regex, then consider matching with the finding pattern, and replacing with the pattern after it:

/\[caption [^<]*(<img[^>]*>)\s*([^[]*)\[\/caption\]/
<figure>$1<figcaption>$2</figcaption></figure>

Here is the code:

$input = "[caption id=\"attachment_15737\" align=\"aligncenter\" width=\"1024\"]<img class=\"wp-image-15737 size-full\" title=\"bathroom counter decor\" src=\"https://roohome.com/wp-content/uploads/2017/11/ivote.jpg\" alt=\"bathroom counter decor\" width=\"1024\" height=\"768\" /> © ivote[/caption]";
$after = preg_replace('/\[caption [^<]*(<img[^>]*>)\s*([^[]*)\[\/caption\]/', '<figure>$1<figcaption>$2</figcaption></figure>', $input);
echo $after;

This outputs the following HTML:

<figure><img class="wp-image-15737 size-full" title="bathroom counter decor"
             src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg"
             alt="bathroom counter decor" width="1024" height="768" />
        <figcaption>© ivote</figcaption>
</figure>

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.