【问题标题】:Having problems with regular expressions with preg_split in PHP在 PHP 中使用 preg_split 的正则表达式有问题
【发布时间】:2010-09-12 04:19:19
【问题描述】:

我有以下输入:

几句话 - 25 还有一些 - 话 - 7 另一个 - 一组 - 单词 - 13

我需要拆分成这个:

[0] = "a few words"
[1] = 25

[0] = "some more - words"
[1] = 7

[0] = "another - set of - words"
[1] = 13

我正在尝试使用 preg_split 但我总是错过结束数字,我的尝试:

$item = preg_split("#\s-\s(\d{1,2})$#", $item->title);

【问题讨论】:

    标签: php regex preg-split


    【解决方案1】:

    使用单引号。我不能强调这一点。 $ 也是字符串结尾的元字符。我怀疑你在拆分时想要这个。

    您可能希望使用类似preg_match_all 的内容进行匹配:

    $matches = array();
    preg_match_all('#(.*?)\s-\s(\d{1,2})\s*#', $item->title, $matches);
    var_dump($matches);
    

    生产:

    array(3) {
      [0]=>
      array(3) {
        [0]=>
        string(17) "a few words - 25 "
        [1]=>
        string(22) "some more - words - 7 "
        [2]=>
        string(29) "another - set of - words - 13"
      }
      [1]=>
      array(3) {
        [0]=>
        string(11) "a few words"
        [1]=>
        string(17) "some more - words"
        [2]=>
        string(24) "another - set of - words"
      }
      [2]=>
      array(3) {
        [0]=>
        string(2) "25"
        [1]=>
        string(1) "7"
        [2]=>
        string(2) "13"
      }
    }
    

    认为您可以从该结构中收集到您需要的信息?

    【讨论】:

    • 该死的,我完全忘记了preg_match的存在,甚至看PHP手册。我知道有一个比 preg_split 更好的 preg_ 函数可以用于我想做的事情。当您停止使用 PHP 开发几年时会发生这种情况:S。谢谢,您的解决方案如我所愿。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多