【问题标题】:Alternative for preg_match_all in eregereg 中 preg_match_all 的替代方案
【发布时间】:2013-11-11 07:57:48
【问题描述】:

我尝试使用 PHP 中的 ereg 函数从使用 PHP 的字符串(可能存储在 CSV 文件中)获取具有特定格式 (02:AA:13:09:45:DE) 的所有数据.

这是我尝试过的:

$string = '02:AA:13:09:45:DE -90 hRm / -21 450 s RX: 1.0 , 1 . TX: 2.0 , MCS 0, 1 . 13:09:13:10:15:5D -33 hRm / -55 5000 s RX: 66.0 , MCS 0, 333 . TX: 66.0, MCS 0, 333 . 17:09:A3:07:30:DC -55 hRm / -22 hRm 456 s RX: 43.0  MCS 0, 434. TX: 43.0 , MCS 0, 43 .'

$pattern='^[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}';
ereg($pattern, $string, $matches);
print_r($matches);

这仅给出第一个值:02:AA:13:09:45:DE由于我不应该使用 preg_match_all(或任何其他 preg 函数),有没有其他方法可以实现这一点(获取所有数据)?

【问题讨论】:

  • 为什么不应该使用 preg* 函数?!
  • 我正在使用 php4 ,在 linux 发行版 openwrt 中也是如此,它根本没有使用 PCRE,并且 ereg 工作正常
  • @deceze 致命错误:调用未定义函数:第 49 行 test.php 中的 preg_match_all()。这是我使用 preg 时得到的结果

标签: php regex text-extraction


【解决方案1】:

嗯,preg_matchpreg_match_all 是最好的选择,而 ereg 是 dead

所以你的选择有点脏。

$items = explode(" ", $string);
foreach($items as $item) {
    $chunks = explode(":", $item);
    // check current item. If consist of 6 hex digits separated by :
    if (count($chunks) == 6) {
        $valid = TRUE;
        // all numbers must be hex!
        foreach($chunks as $chunk) {
            if (!ctype_xdigit($chunk)) {
                $valid = FALSE;
                break;
            }
        }
        if ($valid) {
            echo $item;
        }

    }
}

【讨论】:

  • 我在 linux 发行版 openwrt 中使用 php4,我无法使用 preg 函数(PCRE),这就是我尝试使用 ereg 的原因......我也试过你这样的代码 $items=explode( " ",$string); print_r($items);它在索引0,27和54的数组中给出了mac id ...因此我得到了mac id,但是如果有更多相同格式的macid,我该怎么办?或者有没有其他方法
  • @user2723949 我已经编辑了我的答案,再检查一遍!
猜你喜欢
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 2015-03-03
  • 2015-09-25
  • 2019-12-16
  • 2011-06-20
相关资源
最近更新 更多