查找&;验证字符串中的字符串


find & validate a string in a string

我需要在文件名中找到一个数字。

文件名示例:

_x1984x_testfile.jpg

我需要提取"x"answers"x"括号之间的字符串(仅当它位于文件名的开头时)

然后检查字符串是否为数字,如果是则返回结果。对于上面的例子,代码应该返回1984

我该怎么做?

不需要正则表达式:

$v = explode('x',$string);
if( $v[0] == '_' && is_numeric($v[1]) ) $result = $v[1];

如果您对我的假设不满意,也可以使用不同的if条件,如strlen()。这种方法将比使用regex快得多。

preg_match("/(?<=^_x)'d+(?=x_)/", '_x1984x_testfile.jpg', $m);
print $m[0];

请参阅此处的演示。

preg_match("/^_x('d+)x_/", '_x1984x_testfile.jpg', $matches);
print_r($matches);