2017-10-17 135 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(懶惰),並關閉屬性