我想将jsfiddle URL转换为正确的iframe嵌入。
示例网址:
https://jsfiddle.net/kai_noack/Lc78dr3y
https://jsfiddle.net/kai_noack/Lc78dr3y/
https://jsfiddle.net/kai_noack/h1jf34za/11
https://jsfiddle.net/kai_noack/h1jf34za/11/
并忽略:
https://jsfiddle.net
https://jsfiddle.net/
https://jsfiddle.net/kai_noack
https://jsfiddle.net/kai_noack/
此刻我正在使用什么,另请参见Regex101:https://regex101.com/r/MEHrKO/1
$types = array(
'jsfiddle' => array(
array(
'https{0,1}:\/\/w{0,3}\.*jsfiddle\.net\/([A-Za-z0-9_-]+)[^< ]*',
'<div class="jsfiddle-embed-wrap"><iframe class="iframe-jsfiddle" src="//jsfiddle.net/$1/embedded/result,js,html,css/"></iframe></div>'
),
),
// youtube, replit, ...
}
foreach($types as $t => $ra) {
// $t is youtube, jsfiddle, replit
// $ra is array with replacements $ra[0] regex, $ra[1] embed code
foreach($ra as $r) {
$text = preg_replace('/<a[^>]+>'.$r[0].'<\/a>/i', $r[1], $text);
$text = preg_replace('/(?<![\'"=])'.$r[0].'/i', $r[1], $text);
}
}
但是它不适用于上面的代码,我只得到字符串的kai_noack
部分:
<div class="jsfiddle-embed-wrap"><iframe class="iframe-jsfiddle" src="//jsfiddle.net/kai_noack/embedded/result,js,html,css/">
也许是$1
了吗?
答案 0 :(得分:1)
由于您的字符类中没有kai_noack
:/
,您的模式陷入了[A-Za-z0-9_-]
的困境。
除非我误解了这个问题,否则您只想要小提琴ID和版本号(并忽略用户名前面的所有内容)。
代码:(Demo)
$types = array(
'jsfiddle' => array(
array(
'https?:\/\/(?:www)?\.?jsfiddle\.net[\w\/-]*\/([a-z\d]{8}(?:\/\d+)?)\/?',
'<div class="jsfiddle-embed-wrap"><iframe class="iframe-jsfiddle" src="//jsfiddle.net/$1/embedded/result,js,html,css/"></iframe></div>'
),
),
// youtube, replit, ...
);
$text = 'https://jsfiddle.net/kai_noack/h1jf34za/11/';
foreach($types as $t => $ra) {
// $t is youtube, jsfiddle, replit
// $ra is array with replacements $ra[0] regex, $ra[1] embed code
foreach($ra as $r) {
$text = preg_replace('/<a[^>]+>'.$r[0].'<\/a>/i', $r[1], $text);
$text = preg_replace('/(?<![\'"=])'.$r[0].'/i', $r[1], $text);
}
}
echo $text;
输出:
<div class="jsfiddle-embed-wrap"><iframe class="iframe-jsfiddle" src="//jsfiddle.net/h1jf34za/11/embedded/result,js,html,css/"></iframe></div>
您的模式已经具有i
修饰符,因此[A-Z]
是不必要的。
答案 1 :(得分:0)