-2

How to replace Instagram URLs from a text in embed format with regex?

//Input
$text = 'There is https://www.instagram.com/p/Bes0orNjOIa/?taken-by=kendalljenner and then there was https://www.instagram.com/p/BZMh9qgl8Kw/?taken-by=felix.gaebler';

//Expected output
$text = 'There is <iframe src="//www.instagram.com/p/Bes0orNjOIa/embed"></iframe> and then there was <iframe src="//www.instagram.com/p/BZMh9qgl8Kw/embed"></iframe>';
Felix Gaebler
  • 702
  • 4
  • 23

1 Answers1

0

Regex is for matching Strings, not replacements or something similar. If you want to convert your text into an embed link, this is a way to go:

<?php
    $text = 'There is https://www.instagram.com/p/Bes0orNjOIa/?taken-by=kendalljenner and then there was https://www.instagram.com/p/BZMh9qgl8Kw/?taken-by=felix.gaebler';
    $words = explode(' ', $text);

    $output = array();  

    foreach ($words as $word) {

        if(preg_match('/^https:\/\/www\.instagram\.com\/p\/.{6,}\?/', $word)) {

            $code = explode("/", $word)[4];
            $word = '<iframe src="//www.instagram.com/p/$code/embed"></iframe>';

        } 

        array_push($output, $word);

    }

    echo implode(' ', $output);
?>

Output here: https://i.stack.imgur.com/PuKjh.png

Felix Gaebler
  • 702
  • 4
  • 23