屏幕解决方案的正则表达式

时间:2011-02-09 12:29:03

标签: php regex

我有以下字符串

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

我想要的结果是

540x360

我该怎么办,请建议以后我将能够解决这类问题。

5 个答案:

答案 0 :(得分:4)

$split = explode(' ', $string);
echo $split[0];

http://php.net/manual/en/function.explode.php

答案 1 :(得分:4)

如果您真的想使用正则表达式,可以使用:

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

答案 2 :(得分:2)

无需将字符串转换为数组,这可能非常烦人。

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

可以很容易地修改它以获得分辨率的整数值:

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

答案 3 :(得分: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'
*/

答案 4 :(得分:0)

  $res = str_replace(explode("[", "540x360 [PAR 1:1 DAR 3:2]"), " ", "");
  echo $res[0];