2014-09-29 108 views
0

我輸入的字符串使用正則表達式來獲取所有屬性

$center="[{video('whats-new/reaction-vid1.jpg')} width=\"580\" height=\"326\" alt=\"\" video=\"Zb36h4K2IKQ\"]"; 
$pattern="/\[{video\('([a-zA-Z0-9\/\-\_]+)'\)}\s+(width|height|alt|video)=\"[^\"]+\"\]/"; 
if(preg_match($pattern,$center,$matches)){ 
    print_r($matches);exit; 
} 

但是它無法正常工作。基本上我想要寬度,高度,ALT和視頻的額外屬性。我試了半個小時。任何人都可以將我指向正確的方向嗎?

+0

你的意思** 2個**額外的屬性? – Luke 2014-09-29 09:00:09

回答

0

使用preg_match_all而不是preg_match

<?php 
$center="[{video('whats-new/reaction-vid1.jpg')} width=\"580\" height=\"326\" alt=\"\" video=\"Zb36h4K2IKQ\"]"; 
$pattern="~video\('\K[^']*|(?:width|height|alt|video)=\"\K[^\"]*~"; 
preg_match_all($pattern, $center, $matches); 
print_r($matches); 
?> 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => whats-new/reaction-vid1.jpg 
      [1] => 580 
      [2] => 326 
      [3] => 
      [4] => Zb36h4K2IKQ 
     ) 

) 
+0

對不起,這裏〜video的含義是什麼,因爲$ center是一個可變的句子,它可能有valeus,如「abcded [{video('whats-new/reaction-vid1.jpg')} width = \」580 \「height = \」326 \「alt = \」\「video = \」Zb36h4K2IKQ \「] gef」 – onegun 2014-09-29 09:08:09

+0

正則表達式模式必須包含在分隔符中。我在'〜' – 2014-09-29 09:09:53

+0

內附上上述正則表達式模式,我試過了,似乎你的解決方案也能處理「abcded [{video('whats-new/reaction-vid1.jpg')} width = \」580 \「height = \ 「326 \」alt = \「\」video = \「Zb36h4K2IKQ \」] gef「的情況下,謝謝 – onegun 2014-09-29 09:16:14

相關問題