【问题标题】:converting PHP eregi to preg_match, how do I do it? [duplicate]将 PHP eregi 转换为 preg_match,我该怎么做? [复制]
【发布时间】:2016-08-15 07:42:39
【问题描述】:

我是正则表达式的新手,但我现在没有时间学习它, 但我需要将 eregi("^..?$", $file) 转换为 preg_match() 但我 不知道怎么弄,谁能帮帮我?

也让我对它的工作原理有所了解 很高兴拥有:)

这段代码:

$fileCount = 0;
while ($file = readdir($dh) and $fileCount < 5){
    if (eregi("^..?$", $file)) {
        continue;
    }
    $open = "./xml/".$file;
    $xml = domxml_open_file($open);

    //we need to pull out all the things from this file that we will need to 
    //build our links
    $root = $xml->root();
    $stat_array = $root->get_elements_by_tagname("status");
    $status = extractText($stat_array);

    $ab_array = $root->get_elements_by_tagname("abstract");
    $abstract = extractText($ab_array);

    $h_array = $root->get_elements_by_tagname("headline");
    $headline = extractText($h_array);

    if ($status != "live"){
        continue;
    }
    echo "<tr valign=top><td>";
    echo "<a href=\"showArticle.php?file=".$file . "\">".$headline . "</a><br>";
    echo $abstract;
    echo "</td></tr>";

    $fileCount++;
}

【问题讨论】:

  • 你可能得抓紧时间了,也许我们没有空余时间
  • 快速浏览 Stack 会发现其他提出相同问题的人,也许这可能会有所帮助 stackoverflow.com/questions/2501494/…
  • 与其等着别人为你写代码,不如开始学习正则表达式。这很简单。

标签: php xml eregi


【解决方案1】:

eregi("^..?$", $file) 更改为preg_match("/^\.\.?$/i", $file)

在 eregi 中,您不必为正则表达式添加开启器和关闭器,但对于 preg,您必须这样做(在开始和结束时这两个斜线)。

基本上这个正则表达式匹配所有以 . 开头的文件名。并在那里结束或有另一个。然后在那里结束,所以它会匹配文件 ...

更快的方法是这样的

$fileCount = 0;
while ($file = readdir($dh) and $fileCount < 5){
    if($file != "." && $file != "..") {
        $open = "./xml/".$file;
        $xml = domxml_open_file($open);

        //we need to pull out all the things from this file that we will need to 
        //build our links
        $root = $xml->root();
        $stat_array = $root->get_elements_by_tagname("status");
        $status = extractText($stat_array);

        $ab_array = $root->get_elements_by_tagname("abstract");
        $abstract = extractText($ab_array);

        $h_array = $root->get_elements_by_tagname("headline");
        $headline = extractText($h_array);

        if ($status != "live"){
            continue;
        }
        echo "<tr valign=top><td>";
        echo "<a href=\"showArticle.php?file=".$file . "\">".$headline . "</a><br>";
        echo $abstract;
        echo "</td></tr>";

        $fileCount++;
    }
}

您要尽量避免使用 continuebreak 语句,因为它们不利于良好的代码结构,因为您在查看代码时并不清楚它们为什么存在。

【讨论】:

    【解决方案2】:

    转换后的 preg_match 可以如下所示。

    if (preg_match("/\^|\.\.|\?|\$.*/", $file)) {
        continue;
    }
    

    PS:我用正则表达式测试这个网站。 https://regex101.com/

    【讨论】:

      猜你喜欢
      • 2011-02-09
      • 2013-02-10
      • 2014-12-07
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多