【问题标题】:Regex to slice filename contain string and numerical正则表达式切片文件名包含字符串和数字
【发布时间】:2010-03-27 09:00:44
【问题描述】:

谁能帮我解决这个问题:

我明白了

$filename= "index 198.php";

我用这个失败了

preg_match(" [a-zA-Z0-9]", $filename, $output);

我必须使用什么样的正则表达式模式,所以 $output 数组 将包含一个 number only 值。

【问题讨论】:

    标签: php regex filenames


    【解决方案1】:

    如果您只想从文件名中提取数字,您可以这样做:

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

    它假定文件名只有一组数字。如果有多个数字组,例如index 123 abc 456.php,则只会匹配第一组。

    注意:

    使用的正则表达式是:(\d+)

    • \d[0-9] 的捷径。一个 个位数
    • \d+ :一个或多个数字,基本上 一个数字
    • () :分组并记住比赛。 会记在$matches 数组。
    • ## :分隔符。 preg_ 家庭 函数需要第一个参数 这是位于 a 中的正则表达式 一对分隔符。你可以有 也使用了'/(\d+)/'

    【讨论】:

      【解决方案2】:

      只有一个数字对吗??

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

      要获得更多数字,请使用 preg_match_all()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-27
        • 2011-07-22
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        相关资源
        最近更新 更多