从POST_CONTENT获取YouTube链接不起作用

时间:2019-01-24 作者:FrancMo

我正在尝试从post\\u内容中检索youtube链接,但不起作用。。

function get_yts() {
      $query_args = array(
        \'s\' => \'youtube.com/watch?v=\',
      );

      $posts = get_posts( $query_args );
      foreach ($posts as $p) {
        $matches = array();
        preg_match(\'|http://www.youtube.com/watch\\?v=([a-zA-Z0-9_]+)|\', $p->post_content, $matches);
        echo \'$xxmatches: \' . $matches . \' -> \'. $p->post_content;
      }
    }
结果显示为空数组:

$xxmatches: Array 
我做错了什么?

编辑:

在一些编辑器中找到了更好的正则表达式,但在这里没有:

<?php
        //Enter your code here, enjoy!
$text = \'<!-- wp:core-embed/youtube {"url":"https://www.youtube.com/watch?v=ycsODGR5IDQ","type":"video","providerNameSlug":"youtube","className":"wp-embed-aspect-4-3 wp-has-aspect-ratio"} -->
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
https://www.youtube.com/watch?v=ycsODGR5IDQ
</div></figure>\';

$matches = array();
preg_match(\'/http(?:s?):\\/\\/(?:www\\.)?youtu(?:be\\.com\\/watch\\?v=|\\.be\\/)([\\w\\-\\_]*)(&(amp;)?[\\w\\?‌​=]*)?/\', $text, $text);
echo \'$xxmatches: \' . sizeof($matches);
显示0大小。。

1 个回复
SO网友:FrancMo

好的,这是工作代码:

function get_yts() {
  $query_args = array(
    \'s\' => \'youtube.com/watch?v=\',
  );

  $posts = get_posts( $query_args );
  foreach ($posts as $p) {
    $input_line = $p->post_content;
    $output_array = array();
    preg_match(\'/http(?:s?):\\/\\/(?:www\\.)?youtu(?:be\\.com\\/watch\\?v=|\\.be\\/)([\\w\\-\\_]*)(&(amp;)?[\\w\\?‌​=]*)?/\', $input_line, $output_array);
    print_r($output_array);
  }
}