我正在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']);
到目前为止,我试图做的是:
本质上,我正在寻找一种干净的方法,用嵌入代码替换$ urls,而忽略引号中或$ html标签中以任何其他方式打印的$ urls
正确的答案将涉及使用解析器。要获得更具说服力的解决方案,您可以在正则表达式中使用(*SKIP)(*FAIL)
,例如
<a[^>]*>[^<]*</a>(*SKIP)(*FAIL)|https?:\S+