PHP 字符串与文件操作
字符操作
字符串输出: 字符串输出格式与C语言保持一致,
<?php
// printf 普通的输出函数
$string = "hello lyshark";
$number = 1024;
printf("%s page number = > %u <br>",$string,$number);
// sprintf 将内容输出到缓冲区中
$text = sprintf("float = > %0.2f",$number);
echo "打印输出内容: " . $text . "<br>";
// 打开文件,如果打开失败则提示die中的内容
$url = "./index.php";
fopen($url,"r") or die("Unable to connect $url");
// substr("123123",2,2);
?>
字符串处理函数:
<?php
$string = "@@ hello lyshark @@";
// 字符串左右去除
printf("字符串长度: %d <br>",strlen($string));
printf("字符串截取: %s <br>",substr($string,2,4));
printf("去除左侧空字符: %s <br>",ltrim($string));
printf("去除左侧@字符: %s <br>",ltrim($string,'@'));
printf("去除右侧@字符: %s <br>",rtrim($string,'@'));
printf("去除两边@字符: %s <br>",trim($string,'@'));
// 字符串自动补齐
echo "右边补齐: " . str_pad($string,50,"-") . "<br>";
echo "左边补齐: " . str_pad($string,50,"-",STR_PAD_LEFT) . "<br>";
echo "两边补齐: " . str_pad($string,50,"-",STR_PAD_BOTH) . "<br>";
// 字符串大小写转换
echo "全部小写: " . strtolower($string) . "<br>";
echo "全部大写: " . strtoupper($string) . "<br>";
echo "首字母大写: " . ucwords($string) . "<br>";
// 反转字符串与MD5
echo "反转字符串: " . strrev($string) . "<br>";
echo "MD5 加密: " . md5($string) . "<br>";
?>
字符串比较(字节序): 字节序比较可以使用strcmp/strcasecmp两个函数,只需传入两个字符串即可.
<?php
$username="lyshark"; $password="Abc123^";
// 不区分大小写比较字符串
if(strcasecmp(strtolower($username),"lyshark") == 0)
printf("用户名正确.. <br>");
// 区分大小写验证密码
switch(strcmp($password,"Abc123^"))
{
case 0:
echo "两个字符串相等.";break;
case 1:
echo "第一个大于第二个.";break;
case -1:
echo "第一个小于第二个.";break;
}
// 字符串实现冒泡排序
$info= array("file11.txt","file22.txt","file1.txt","file2.exe");
function MySort($array)
{
for($x=0; $x<count($array); $x++)
for($y=0;$y<count($array)-1; $y++)
if(strnatcmp($array[$y],$array[$y+1]))
{
$tmp = $array[$y];
$array[$y] = $array[$y+1];
$array[$y+1] = $tmp;
}
return $array;
}
print_r(MySort($info));
?>
字符串替换/切割: 将字符串切割为多个部分,替换字符串,与连接字符串等操作.
<?php
// 实现截取文件后缀
function getFileName($url)
{
$location = strrpos($url,"/")+1; // 获取URL中最后一个/出现的位置
$fileName = substr($url,$location); // 截取从location位置到结尾的字符
return $fileName;
}
echo getFileName("http://www.baidu.com/index.php") . "<br>";
echo getFileName("file://c://windows/php.ini") . "<br>";
// 实现字符串替换
$string = "BASH Linux PHP MySQL Ruby Metasploit linux";
echo "将Linux替换为Win: " . str_replace("Linux","Windows",$string,$count) . "<br>";
echo "将Linux替换为Win: " . str_ireplace("Linux","Windows",$string,$count) . "<br>";
$search = array("http","www","jsp","com"); // 搜索字符串
$replace = array("https","bbs","php","net"); // 替换字符串
$url = "http://www.baidu.com/index.jsp";
echo "数组替换: " . str_replace($search,$replace,$url) . "<br>";
// 实现字符串切割与链接
$info = "Linux Apache MySQL PHP Web";
$str_cat = explode(" ",$info);
echo "切割后: " . $str_cat[1] . $str_cat[2] . "<br>";
$info = "root:*:0:0::/home/dhat:/bin/bash";
list($user,$pass,$uid,$gid,,$home,$shell) = explode(":",$info);
echo "切割后: 用户-> " . $user . " 终端Bash -> " . $shell . "<br>";
$info = array("linux","Apache","MySQL","PHP");
echo "链接字符串: " . implode("+",$info) . "<br>";
echo "链接字符串: " . join("+",$info) . "<br>";
?>
正则匹配字符串: 通过使用正则我们同样可以对字符串进行匹配,切片,组合,查找等操作.
<?php
/*
邮箱: '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/'
正整数: '/^\d+$/'
qq号码:'/^\d{5,11}$/'
手机号码: '/^1(3|4|5|7|8)\d{9}$/'
*/
// 简单的正则匹配方法
$pattern = "/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
$subject = 'aaa 1181506874@qq.com test admin@blib.cn ddd';
$recv = preg_match_all($pattern, $subject,$match,PREG_SET_ORDER);
echo "匹配记录: " . $recv . "条, 值: " . $match[0][0] . "," . $match[1][0] . "<br>";
// 匹配数组中符合条件的字符串
$array = array("LinuxHat","Nginx 2.2.3","Apache 2.29","PHP");
$pattern_version = preg_grep("/^[a-zA-Z ]+(\d|\.)+$/",$array);
print_r($pattern_version); echo "<br>";
// 正则实现字符串替换
$pattern = "/[!@#$]/";
$text = "你@好!,当前日#期 01/25/2020 总#共365天";
echo "替换特殊符号为空: " . preg_replace($pattern,"",$text) . "<br>";
$pattern = "/(\d{2})\/(\d{2})\/(\d{4})/";
echo "替换实现时间翻转: " . preg_replace($pattern,"\${3}-\${1}-\${2}",$text) . "<br>";
// 正则实现字符串切割
$keyworks = preg_split("/[\s,]/","php,nginx, mysql python");
echo "切割字符串为数组: "; print_r($keyworks); echo "<br>";
$keyworks = preg_split("//","lyshark",-1,PREG_SPLIT_NO_EMPTY);
echo "将字符串切割为字符: "; print_r($keyworks); echo "<br>";
?>
文件操作
读文件基本信息: 文件基本信息包括文件类型,文件的创建日期等基本信息.
<?php
$Path = "C://Windows/System32/drivers/etc/hosts";
echo "文件类型: " . filetype($Path) . "<br>";
echo "文件建立时间: " . date("Y年m月j日",filectime($Path))."<br>";
echo "文件最后更改时间: " . date("Y年m月j日",filemtime($Path))."<br>";
echo "文件最后打开时间: " . date("Y年m月j日",fileatime($Path))."<br>";
if(file_exists($Path))
printf("文件存在 <br>");
if(is_file($Path))
printf("是一个文件 <br>");
if(is_dir($Path))
printf("是一个目录 <br>");
if(is_readable($Path))
printf("文件可读 <br>");
if(is_writable($Path))
printf("文件可写 <br>");
if(is_executable($Path))
printf("文件可执行 <br>");
?>
判断文件类型: 虽然我们可以通过filetype()
函数判断文件类型,但是不够具体,如下是具体的判断流程.
<?php
$Path = "C://Windows/System32/drivers/etc/hosts";
function GetFileType($FileName)
{
switch(filetype($FileName))
{
case "file": $type = "普通文件"; break;
case "dir": $type = "目录文件"; break;
case "block": $type = "块设备文件"; break;
case "fifo": $type = "命名管道文件"; break;
case "link": $type = "符号文件"; break;
case "unknown": $type = "未知文件"; break;
default: $type = "没有检测到"; break;
}
return $type;
}
$type = GetFileType($Path);
printf("文件类型: %s <br>",$type);
?>
获取文件大小:
<?php
$Path = "C://Windows/System32/drivers/etc/hosts";
function GetFileSize($bytes)
{
if($bytes >= pow(2,40))
{
$return = round($bytes/pow(1024,4),2);
$suffix = "TB";
}else if($bytes >= pow(2,30))
{
$return = round($bytes/pow(1024,3),2);
$suffix = "GB";
}else if($bytes >= pow(2,20))
{
$return = round($bytes/pow(1024,2),2);
$suffix = "MB";
}else if($bytes >= pow(2,10))
{
$return = round($bytes/pow(1024,1),2);
$suffix = "KB";
}else
{
$return = $bytes;
$suffix = "Byte";
}
return $return . " " . $suffix;
}
$ret = GetFileSize(filesize($Path));
echo "文件实际大小: " . $ret . "<br>";
?>
文件与目录解析:
<?php
// 返回文件基本信息数组
$Path = "C://Windows/System32/drivers/etc/hosts";
$FilePro = stat($Path);
echo "文件基本信息: "; print_r(array_slice($FilePro,13)); echo "<br>";
// 返回路径中的 page.php 文件名
$Path = "/var/www/html/page.php";
echo "带文件扩展名输出: " . basename($Path) . "<br>";
echo "不带文件扩展名输出: " . basename($Path,".php") . "<br>";
// 返回路径的所在位置
echo "文件所在位置: " . dirname($Path) . "<br>";
// 返回目录中文件详细信息
$path_parts = pathinfo($Path);
echo "路径: " . $path_parts["dirname"] . "<br>";
echo "文件: " . $path_parts["basename"] . "<br>";
echo "扩展名: " . $path_parts["extension"] . "<br>";
?>
文件读写操作: 读写文件首先需要使用fopen函数打开文件,然后使用fread读取,fwrite写入,最后使用fclose释放句柄.
<?php
// 从文件中读出前100个字节
$handle = fopen("c://test.log","r") or die("Open File Err");
$context = fread($handle,100);
echo $context;
fclose($handle);
// 循环从文件中读取全部数据
$handle = fopen("c://test.log","r") or die("Open File Err");
$context = "";
while(!feof($handle))
{
$context = fread($handle,1024);
}
fclose($handle);
echo $context;
// 另一种读取全文的方式
$handle = fopen("c://test.log","r") or die("Open File Err");
$context = fread($handle,filesize("c://test.log"));
fclose($handle);
echo $context;
// 每次读入一个字符,直到读取结束
$handle = fopen("c://test.log","r") or die("Open File Err");
while(false !==($char = fgetc($handle)))
{
echo $char . "<br>";
}
// 读取远程文件,并输出
$file = fopen("http://www.baidu.com","r");
while(!feof($file))
{
$line = fgets($file,1024);
echo $line;
}
fclose($file);
// 文件写入数据
$handle = fopen("c://new.txt","w") or die("open file error");
for($row=0; $row<10; $row++)
{
fwrite($handle,$row . "www.baidu.com \n");
}
fclose($handle);
?>
遍历文件目录: 遍历目录中文件,主要用到opendir打开为文件,readdir每次读入一条记录,最后closedir关闭句柄.
<?php
$Path = "d://";
$dir_handle = opendir($Path);
echo "<table border='1' width='600' cellspacing='0' cellpadding='0' align='center'>";
echo "<caption><h2>目录: " . $Path . "</h1></caption>";
echo "<tr align='left' bgcolor='#ddddddd'>";
echo "<th>文件名</th><th>文件大小</th><th>文件类型</th><th>修改时间</th></tr>";
while($each = readdir($dir_handle))
{
$dir_file_path = $Path . "/" . $each; // 将目录与文件连接起来
if($num++ % 2 == 0) // 控制奇数行与偶数行不同的颜色输出
$bgcolor='#ffccf';
else
$bgcolor='#ccfff';
echo "<tr bgcolor=" . $bgcolor . ">";
echo "<td>" . $dir_file_path . "</td>";
echo "<td>" . filesize($dir_file_path) . "</td>";
echo "<td>" . filetype($dir_file_path) . "</td>";
echo "<td>" . date("Y/n/t",filemtime($dir_file_path)) . "</td>";
echo "</tr>";
}
echo "</table>";
closedir($dir_handle);
echo "目录: " . $Path . "总共有: " . $num . " 个文件" . "<br>";
?>
统计目录总容量: 计算文件磁盘目录的总大小,具体思路是递归遍历将每次遍历到的文件大小存入变量递增.
<?php
echo "磁盘剩余大小: " . disk_free_space("c://") . "<br>";
echo "磁盘总计大小: " . disk_total_space("c://") . "<br>";
function GetDirSize($directory)
{
$dir_size = 0;
// 首先打开目录,并判断目录是否打开成功
if($dir_handle = @opendir($directory))
{
// 循环每次读入一个目录下的所有文件
while($filename = readdir($dir_handle))
{
// 判断目录文件,排除. .. 两个无效路径
if($filename != "." && $filename != "..")
{
$file_path = $directory . "/" . $filename;
// 如果是目录,则需要继续递归调用自身函数
if(is_dir($file_path))
$dir_size += GetDirSize($file_path);
// 如果是文件则统计大小
if(is_file($file_path))
$dir_size += filesize($file_path);
}
}
}
closedir($dir_handle);
return $dir_size;
}
$dir_size = GetDirSize("D://htmlcss/");
echo "目录大小: " . round($dir_size/pow(1024,2),2). "MB" . "<br>";
echo "目录大小: " . round($dir_size/pow(1024,1),2). "KB" . "<br>";
?>
目录递归拷贝: 如果需要拷贝单个文件可以直接使用copy函数,如果要拷贝目录则需要递归拷贝.
<?php
function CopyFileDir($dir_src,$dir_dst)
{
if(is_file($dir_dst))
{
printf("目标不是目录,无法执行.");
return;
}
if(!file_exists($dir_dst))
mkdir($dir_dst);
// 首先打开目录,并判断目录是否打开成功
if($dir_handle = @opendir($dir_src))
{
// 循环每次读入一个目录下的所有文件
while($filename = readdir($dir_handle))
{
// 判断目录文件,排除. .. 两个无效路径
if($filename != "." && $filename != "..")
{
$sub_file_src = $dir_src . "/" . $filename;
$sub_file_dst = $dir_dst . "/" . $filename;
if(is_dir($sub_file_src))
CopyFileDir($sub_file_src,$sub_file_dst);
if(is_file($sub_file_src))
copy($sub_file_src,$sub_file_dst);
}
}
closedir($dir_handle);
}
return $dir_size;
}
// 将d://test目录,拷贝到c://test
CopyFileDir("d://test","c://test");
?>
目录递归删除: 递归删除需要先调用unlink函数将目录中每个文件都删掉,然后赞调用rmdir删除空目录.
<?php
function DelFileDir($directory)
{
// 判断目录是否存在
if(file_exists($directory))
{
if($dir_handle = @opendir($directory))
{
while($filename = readdir($dir_handle))
{
if($filename!='.' && $filename != "..")
{
$sub_file = $directory . "/" . $filename;
if(is_dir($sub_file))
DelFileDir($sub_file);
if(is_file($sub_file))
unlink($sub_file);
}
}
closedir($dir_handle);
rmdir($directory);
}
}
}
// 删除c://test整个目录
DelFileDir("c://test");
?>
文章出处:https://www.cnblogs.com/LyShark/articles/13380478.html
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!