【问题标题】:Match a string using some regular expression使用一些正则表达式匹配一个字符串
【发布时间】:2014-08-12 22:03:58
【问题描述】:

我有一个如下所示的字符串:

089 / 23249841noch not deposited

我想从字符串中提取以下部分:

089 / 23249841

如何使用 PHP 和正则表达式做到这一点?

【问题讨论】:

    标签: php regex


    【解决方案1】:

    假设你想匹配第一个字母之前的所有内容,

    preg_match("/(^[^a-z]+)/i", "089 / 23249841noch not deposited", $match)
    

    $match 将包含,

    Array
    (
        [0] => 089 / 23249841
        [1] => 089 / 23249841
    )
    

    【讨论】:

    • 不客气@MubinKhalid,很高兴它按你的意愿工作:)
    【解决方案2】:

    仅举一个例子,为此编写一个适当的正则表达式有点棘手。但是,这个应该可以工作:

    [0-9 /]+
    

    或者,在完整的 PHP 代码中:

    $str = '089 / 23249841noch not deposited';
    $matches = array();
    if (preg_match('[0-9 /]+', $str, $matches)) {
        var_dump($matches);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2021-12-27
      相关资源
      最近更新 更多