You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP preg_replace替换Twitch Clips链接异常:片段ID未正确替换至指定位置

Fixing Twitch Clip to iFrame Replacement in PHP

Let's break down why your replacement isn't working as expected. The core issue is your regex's non-greedy .*? match—since there's no clear stopping condition, it's matching nothing (the smallest possible string) right after https://clips.twitch.tv/. That leaves $1 empty, so the actual clip ID gets dumped after the iFrame tag instead of being inserted into the clip= parameter.

Here's the corrected code:

$str = preg_replace('/https:\/\/clips.twitch.tv\/([^\s]+)/', '<iframe src="https://clips.twitch.tv/embed?autoplay=false&clip=$1&tt_content=embed&tt_medium=clips_embed" width="640" height="360" frameborder="0" scrolling="no" allowfullscreen="true"></iframe>', $text);

What changed & why:

  • Replaced .*? with ([^\s]+): This pattern matches one or more non-whitespace characters, which perfectly captures Twitch's clip IDs (they never include spaces). This ensures we grab the full clip ID without stopping early.

If you want an even stricter match (since Twitch clip IDs only use letters, numbers, and underscores), you can use this more precise pattern:

$str = preg_replace('/https:\/\/clips.twitch.tv\/([\w]+)/', '<iframe src="https://clips.twitch.tv/embed?autoplay=false&clip=$1&tt_content=embed&tt_medium=clips_embed" width="640" height="360" frameborder="0" scrolling="no" allowfullscreen="true"></iframe>', $text);

[\w] is shorthand for [A-Za-z0-9_], which exactly matches the character set Twitch uses for clip IDs. This prevents accidentally capturing extra characters (like punctuation) that might follow the link.

内容的提问来源于stack exchange,提问作者indiehjaerta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:17:24