2014-09-29 111 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