【问题标题】:Replace Instagram URL to Embed将 Instagram URL 替换为嵌入
【发布时间】:2018-07-27 19:07:20
【问题描述】:

如何用正则表达式替换嵌入格式文本中的 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>';

【问题讨论】:

  • 你的目标到底是什么?正则表达式用于匹配 Strings,而不是替换或类似的东西。
  • $text = It was... 如果这是您的真实代码,则会向您抛出 undefined constant 警告。
  • 这个问题不清楚,原因太多了。
  • @FelixGaebler 我想为 URL Instagram 应用嵌入模式。
  • @FunkFortyNiner 当然,我知道)

标签: php regex curl instagram embed


【解决方案1】:

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

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

【讨论】:

  • 谢谢!但这怎么能同时应用于多个 URL 呢?例如,我在 $text 变量中有 2 个引用。
  • 用逗号分隔?还是在数组中更好?
  • 我的意思是我的例子。 $text = '它是...';
  • 所以通过正则表达式自动识别网址,然后将它们嵌入! :) 为什么不这么说
  • 您的示例允许您操作单个 URL。需要在一个变量中使用多个 URL。
猜你喜欢
  • 2018-08-13
  • 1970-01-01
  • 2012-01-02
  • 2015-06-06
  • 2014-01-21
  • 1970-01-01
  • 2014-01-21
  • 2013-07-21
  • 2013-03-27
相关资源
最近更新 更多