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

Insert embed code only in place of urls that are not in href

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

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

A post 的 body 可能看起来有点像这样:

    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>

在这整个postbody中,模块匹配一个url(https://vimeo.com/id1),然后用str_replace()替换每个url 使用生成的嵌入代码。

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

到目前为止我尝试做的是:

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

正确的答案是使用解析器。
对于更 hacky 的解决方案,您可以在正则表达式中使用 (*SKIP)(*FAIL),例如

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

参见a demo on regex101.com