2017-10-17 136 views
-1

我需要捕获作为iframe标记内部网址一部分的ID。 我知道这可以用正则表达式来完成,但我不是很擅长,我做了一些尝试,但不能得到一个结果,IFRAME应该是这样(ID可能会有所不同):在iframe标记中选择部分网址

<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe> 

而ID我想得会是这样:

ph57d6z9fa1349b 
+0

这是大材小用? [https://3v4l.org/v01sD](https://3v4l.org/v01sD)。的xD – FirstOne

回答

1

你可以在双引号用正则表达式分割字符串。

$re = '/\<iframe[^\>]+src\="(.+?)\/([A-Za-z0-9]+)"/'; 
$str = '<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>'; 

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); 

// Print the entire match result 
var_dump($matches); 

如果要列出ID码(如 'ph57d6z9fa1349b'),那么你可以这样做:

<?php 
$re = '/\<iframe[^\>]+src\="(.+?)\/([A-Za-z0-9]+)"/'; 
$str = '<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>'; 

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); 

foreach ($matches as $match) { 
    $id = $match[2]; // The required id code 
    echo $id;   // Echo it 
} 
?> 
0

此正则表达式的源属性相匹配,并把你的desided ID组1
src=".+\/(.+?)"

  • 第一部分src="属性的开头匹配
  • .+\/的URL体相匹配,直到最后一个斜线(贪婪)
  • (.+?)"匹配您的ID(懒惰),并关闭属性