2011-02-09 85 views
2

我有以下字符串爲屏解決方案正則表達式

540x360 [PAR 1:1 DAR 3:2] 

我要的結果是

540x360 

我該怎麼辦,請建議這樣,未來我將能夠解決這些有點問題我的自我。

回答

4

如果你真的想用一個正則表達式,你可以使用:

$string = "540x360 [PAR 1:1 DAR 3:2]"; 
$matches = array(); 
preg_match('/^(\d+x\d+)/i', $string, &$matches); 
echo $matches[0]; 
0
$res = str_replace(explode("[", "540x360 [PAR 1:1 DAR 3:2]"), " ", ""); 
    echo $res[0]; 
+2

這將是結果後返回一個空格:「540x360」 – 000 2011-02-09 12:34:54

+0

@Schattenbaum:剛剛編輯 – oopbase 2011-02-09 12:39:25

2

無需CONVER的字符串數組,可以是很煩人。

sscanf($str, "%s ", $resolution); 
// $resolution = 540x360 

這可以很容易地修改,以獲得分辨率的整數值:

sscanf($str, "%dx%d ", $resolution_w, $resolution_h); 
// $resolution_w = 540 
// $resolution_h = 360 
1
<?php 

function extractResolution($fromString, $returnObject=false) 
{ 
    static $regex = '~(?P<horizontal>[\d]+?)x(?P<vertical>[\d]+?)\s(?P<ignorable_garbage>.+?)$~'; 

    $matches = array(); 
    $count = preg_match($regex, $fromString, $matches); 
    if ($count === 1) 
    { 
     /* 
     print_r($matches); 

     Array 
     (
      [0] => 540x360 [PAR 1:1 DAR 3:2] 
      [horizontal] => 540 
      [1] => 540 
      [vertical] => 360 
      [2] => 360 
      [ignorable_garbage] => [PAR 1:1 DAR 3:2] 
      [3] => [PAR 1:1 DAR 3:2] 
     ) 
     */ 

     $resolution = $matches['horizontal'] . 'x' . $matches['vertical']; 

     if ($returnObject) 
     { 
      $result = new stdClass(); 
      $result->horizontal = $matches['horizontal']; 
      $result->vertical = $matches['vertical']; 
      $result->resolution = $resolution; 
      return $result; 
     } 
     else 
     { 
      return $resolution; 
     } 
    } 
} 

$test = '540x360 [PAR 1:1 DAR 3:2] '; 

printf("Resolution: %s\n", var_export(extractResolution($test, true), true)); 
/* 
Resolution: stdClass::__set_state(array(
    'horizontal' => '540', 
    'vertical' => '360', 
    'resolution' => '540x360', 
)) 
*/ 

printf("Resolution: %s\n", var_export(extractResolution($test, false), true)); 
/* 
Resolution: '540x360' 
*/