请为初学者解释这个 php substr 代码


Please explain this php substr code for a total beginner

<?php
$imgdir = 'img/';
$allowed_types = array('png','jpg','jpeg','gif'); //Allowed types of files
$dimg = opendir($imgdir);//Open directory
while($imgfile = readdir($dimg))
{
//please explain this part!!
if( in_array(strtolower(substr($imgfile,-3)),$allowed_types) OR
    in_array(strtolower(substr($imgfile,-4)),$allowed_types) )
{$a_img[] = $imgfile;}
}
$totimg = count($a_img);
for($x=0; $x < $totimg; $x++){echo "<li><img src='" . $imgdir . $a_img[$x] . "'/></li>"
;}?>

明白,这就像婴儿步骤,但我的问题是:我阅读了 php 手册,但我真的不明白为什么 substr 部分是这样的!请帮忙!谢谢!

它正在检查文件名的最后 3 个字符,然后检查最后 4 个字符以获取扩展名,并查看它是否在允许类型的数组中。

但是,改

pathinfo()可能会更好。 http://php.net/manual/en/function.pathinfo.php

$path_parts = pathinfo($imgfile);
if( in_array(strtolower($path_parts['extension']),$allowed_types) ) {
    $a_img[] = $imgfile;
}

让我像婴儿语言一样向你解释:D

substr 有两个参数,一个字符串和一个数字。字符串是文本或字符,如文件名等,数字是您要使用它的字符数。

如果数字是正数,那么它将从左侧获取字符,

如果数字为负数,则它将从右侧获取字符。在您的代码中:

substr($imgfile,-3)  // takes three characters from left

这意味着,取图像文件名的最后三个字符,即文件的扩展名,并且

substr($imgfile,-4)  // takes four characters from right side

表示取最后四个字符。

在你允许的类型数组中:

$allowed_types = array('png','jpg','jpeg','gif');

您有三个字符扩展名和一个四个字符扩展名,因此这两个 substr 用于这些目的。

我希望我用简单的话为您解释。

谢谢

substr($imgfile,-3) ; 等于substr($imgfile, strlen($imgfile)-4);

这意味着您只收到字符串的最后 3 个字符。在这种情况下,作者首先检查最后 3 个字符,然后检查最后 4 个字符,以查看它是否是允许的扩展名。

有关更多信息,请再次检查文档: 字符串 substr ( 字符串 $string , int $start [, int $length ] (