仅插入嵌入代码代替不在href中的URL

问题描述 投票:0回答:1

我正在drupal 8网站上自定义模块,在那里某些vimeo或youtube url转换为嵌入式iframe视频。该模块本身很好用,但是当有标签时会出现问题

<a href="https://vimeo.com/videoid">Some text</a>.

帖子的正文可能看起来像这样:

    https://vimeo.com/id1   //this line should get replaced with embed code by module

    <a href="https://vimeo.com/id1"> Check out this video </a> //here, anything that is in href="" should not be replaced
on <a href="https://vimeo.com"> Vimeo </a>

在整个文章正文中,模块匹配一个URL(https://vimeo.com/id1),然后使用str_replace()将每个URL替换为生成的嵌入代码。

$embed_code = $this->convertVimeoUrlToEmbedCode($url);
$return['text'] = str_replace($url, $embed_code, $return['text']);

到目前为止,我试图做的是:

  • 在href标记中的URL处放置一个占位符文本,然后用嵌入代码替换所有URL,然后将URL放回占位符。
  • 从引号之间的文本中删除所有URL(已解决问题的一半)

本质上,我正在寻找一种干净的方法,用嵌入代码替换$ urls,而忽略引号中或$ html标签中以任何其他方式打印的$ urls

php regex drupal str-replace
1个回答
0
投票

正确的答案将涉及使用解析器。要获得更具说服力的解决方案,您可以在正则表达式中使用(*SKIP)(*FAIL),例如

<a[^>]*>[^<]*</a>(*SKIP)(*FAIL)|https?:\S+

请参见a demo on regex101.com

© www.soinside.com 2019 - 2024. All rights reserved.