-3

我是正则表达式的新手,但我现在没有时间学习它,但我需要将 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++;
}
4

2 回答 2

0

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

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

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

更快的方法是这样的

$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++;
    }
}

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

于 2016-08-15T08:02:12.990 回答
0

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

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

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

于 2016-08-15T08:03:36.463 回答