PHP - 获得这些值的更好方法?

时间:2013-11-17 10:10:46

标签: php regex substr

$image= "some-name-of-my-image-640x480-123.jpg"

我需要提取640x480123

现在对我有用的是:

list($dirname, $basename, $extension, $filename) = array_values(pathinfo($image));
$new = substr($filename, 0, strrpos($filename, '-')); //some-name-of-my-image-640x480
$post_id = substr($filename, strrpos($filename, '-')+1); //123
$resolution = substr($new, strrpos($new, '-')+1); //640x480

是否有更简单(更聪明)的东西来实现同样的目标?

2 个答案:

答案 0 :(得分:4)

您可以使用以下正则表达式:([0-9]+)x([0-9]+)-([0-9]+)

或者,正如评论中所建议的那样:(\d+)x(\d+)-(\d+)

解析名称:

preg_match("/(\d+)x(\d+)-(\d+)/", $file_name, $data);

$data中你会得到:

Array
(
    [0] => 640x480-123
    [1] => 640
    [2] => 480
    [3] => 123
)

答案 1 :(得分:4)

对于对正则表达式过敏且使用PHP> = 5.2.0的任何人:

$data = array_slice(explode('-', pathinfo($image, PATHINFO_FILENAME)), -2);     

$data中你会得到:

Array
(
    [0] => 640x480
    [1] => 123
)