PHP:preg_match():分隔符不能是字母数字或反斜杠


PHP: preg_match(): Delimiter must not be alphanumeric or backslash

我正在制作一个php文件来搜索引入名称的目录中的图像,但函数preg_match返回此错误:"警告:preg_math():分隔符不能是字母数字或反斜杠"。代码是这样的:

<?php
$ruta='fotos'; 
// Usamos dir 
$dir=dir($ruta);     
// Archivo a Buscar 
$busqueda=$_POST['busqueda'] ;
$buscar = $busqueda; 
// Recorremos los Archivos del Directorio 
while ($elemento = $dir->read()) 
{     
     // Evitamos el . y ... 
    if ( ($elemento != '.') and ($elemento != '..')) 
    { 
        // Vemos si Existe el Archivo 
        if (preg_match($buscar, $elemento) AND is_file($ruta.$elemento)  ) 
        { 
            echo " Archivo : $elemento <br>"; 
        } 

    }       
}     
?>

它为循环中的每个迭代提供了警告。我是ve trying to fix it but I can。有人能帮我吗?

错误是由preg_match($buscar, $elemento)引起的。该调用的成功或失败取决于$buscar的值。然而,由于,$buscar来自用户

$busqueda=$_POST['busqueda'] ;
$buscar = $busqueda;

首先,没有多少用户能够制定正则表达式,因此向用户询问正则表达式可能不是一个好主意。我不知道你是否打算这样做,因为变量$buscar以前被定义为$buscar = "arica"(为了不同的目的重用同一个变量不是一个好主意,这会让开发人员感到困惑。)

其次,作为模式传递给preg_match()的字符串必须包含分隔符。我不知道$buscar = "arica"中的a是否是一个有效的分隔符,它肯定是一个不寻常的分隔符(通常选择/作为分隔符,但其他也可以)。所以应该是

$buscar = "/arica/";

但请注意,/arica/无论如何都不会用作正则表达式,因为我前面说过。

你没有对这个问题做足够的研究。

$buscar = "arica"; 

我想是你的模式。我在这里没有看到任何正则表达式,但在某种程度上它需要有分隔符。

来自php手册:

当使用PCRE函数时,需要用分隔符将模式括起来。分隔符可以是任何非字母数字、非反斜杠、非空白字符。

常用的分隔符是正斜杠(/)、哈希符号(#)和波浪号(~)。以下都是有效分隔模式的示例。

所以你需要使用其中一个分隔符,例如

$buscar = "/arica/"; 

但是,在您的情况下,删除preg_match()并简单使用

$buscar == $elemento

它也会这么做。

此外,您应该考虑使用DirectoryTerator。有了它,你可以将代码更改为

$ruta='fotos'; 
$busqueda=$_POST['busqueda'] 
$iterator = new DirectoryIterator($ruta);
foreach ($iterator as $fileinfo) {
  if ($fileinfo->isFile() && $fileinfo->getFileName() == $busqueda) {
       echo " Archivo : $elemento <br>"; // here can be added 'break' I guess there is only 1 file with name you search for.
  }
}

我不知道你到底想实现什么,但也许你应该使用file_exists();