Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 屏幕解的正则表达式_Php_Regex - Fatal编程技术网

Php 屏幕解的正则表达式

Php 屏幕解的正则表达式,php,regex,Php,Regex,我有下面的字符串 540x360 [PAR 1:1 DAR 3:2] 我想要的结果是 540x360 我该怎么办,请建议,以便将来我能自己解决此类问题 $split = explode(' ', $string); echo $split[0]; 如果确实要使用正则表达式,可以使用: $string = "540x360 [PAR 1:1 DAR 3:2]"; $matches = array(); preg_match('/^(\d+x\d+)/i', $string, &$m

我有下面的字符串

540x360 [PAR 1:1 DAR 3:2] 
我想要的结果是

540x360
我该怎么办,请建议,以便将来我能自己解决此类问题

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

如果确实要使用正则表达式,可以使用:

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

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

sscanf($str, "%s ", $resolution);
// $resolution = 540x360
可以很容易地对其进行修改,以获得分辨率的整数值:

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

这将在结果后返回一个空格:“540x360”很好。如果分辨率不是在开始时,或者包含空格,这一点尤其有用:
800x600
将严重爆炸,但正则表达式可以轻松调整以支持它。我可能会把它写成
/(\d+)\s*x\s*(\d+)/I
,以捕获这两个数字。另外,欢迎来到Stack Overflow。亲爱的down投票者,请解释一下你为什么投票否决我。真诚地说,卡里姆79。
sscanf($str, "%dx%d ", $resolution_w, $resolution_h);
// $resolution_w = 540
// $resolution_h = 360
<?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'
*/