将 Instagram URL 替换为嵌入

Replace Instagram URL to Embed

如何使用正则表达式替换嵌入格式文本中的 Instagram URL?

//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>';

正则表达式用于匹配字符串,而不是替换或类似的东西。 如果您想将文本转换为嵌入 link,这是一种方法:

<?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);
?>

此处输出:https://i.imgur.com/bHWKF6D.png