开发者

Regex to slice filename contain string and numerical

can anybody help me solve this :

i got

$filename= "index 198.php";

i use this and failed

preg_match(" [a-zA-Z0-9]", $filename, $output);
开发者_运维知识库

what kind of regex pattern i have to use so the $output array will be consist a number only value.


If you want to extract just the number from the file name you can do:

$filename= "index 198.php";
if(preg_match('#(\d+)#',$filename,$matches))
    echo $matches[1]; // prints 198

It assumes that the file name has just one group of digits. In case if there are more than one group of digits like index 123 abc 456.php only the first group will be matched.

Note:

The regex used is: (\d+)

  • \d : short cut for [0-9]. A single digit
  • \d+ : one or more digits, basically a number
  • () : to group and remember the match. It will be remembered in $matches arrray.
  • ## : delimiters. preg_ family of functions expect the 1st argument which is the regex to be inside a pair of delimiter. You could have used '/(\d+)/' too.


a number only right??

$filename= "index 198.php";
preg_match_all("/(\d+)/",$filename,$matches);
print_r($matches[1]);

to get more numbers, use preg_match_all()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜