#3 PHP 文件操作

2011-05-03
// 创建目录
if (!is_dir("mydirectory")) {
    mkdir("mydirectory");
} else {
    die("目录已存在");
}
// 创建多级目录
mkdir("path/to/my/directory", 0777, true);

// 删除目录
rmdir("newdir");

// 打开目录
$dir = opendir(".");

// 读目录
while($file = readdir($dir)) {
    echo $file . "<br />";
}

// 读目录 2
$directory = '/path/to/dir';
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directory,
        RecursiveDirectoryIterator::SKIP_DOTS), // 忽略 . / ..
    RecursiveIteratorIterator::SELF_FIRST); // 深度优先
foreach ($iterator as $item) {
    if ($item->isDir()) {
        echo "目录: " . $item->getPath() . "\n";
    } else {
        echo "文件: " . $item->getPathname() . "\n";
    }
}

// 关闭目录
closedir($dir);

// 打开文件
$myfile = fopen("example.txt", "r");

// 读文件
$data = fread($myfile, filesize("example.txt"));

// 写文件
fwrite($myfile, "This is some text");

fclose($myfile);

// 读文件
$data = file_get_contents("example.txt");

// 写文件
file_put_contents("example.txt", "This is some text");

// 删除文件
unlink("example.txt");

#2 PHP 时间处理

2011-05-02

date/time/strtotime

time()  # 获得当前时间戳
date(fmtStr, timestamp)

strtotime("+1 day")
strtotime("next Thursday")
strtotime("last Thursday")
# 字符串 => 时间戳
php -r 'var_dump(strtotime("today"));' # 零点
php -r 'var_dump(strtotime("2011"));'
php -r 'var_dump(strtotime("2011-12"));'
php -r 'var_dump(strtotime("2011-12-13"));'
php -r 'var_dump(strtotime("2011-12-13 06:00:00"));'

# 时间戳 => 字符串
php -r 'var_dump(date("Y-m-d H:i:s", 0));'

DateTime

  • DateTimeInterface
  • DateTime
  • DateTimeImmutable
  • DateTimeZone
  • DateInterval
  • DatePeriod 实现 Traversable 接口
// DateTimeInterface::ATOM = "Y-m-d\TH:i:sP";
// DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
// DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO";
// DateTimeInterface::RFC822 = "D, d M y H:i:s O";
// DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
// DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
// DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
// DateTimeInterface::RFC7231 = "D, d M Y H:i:s \G\M\T";
// DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
// DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP";
// DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP";
// DateTimeInterface::RSS = "D, d M Y H:i:s O";
// DateTimeInterface::W3C = "Y-m-d\TH:i:sP";

$dateTime = new DateTime();

foreach ([
    'ATOM',
    'COOKIE',
    'ISO8601',
    'RFC822',
    'RFC850',
    'RFC1036',
    'RFC1123',
    'RFC2822',
    'RFC3339',
    'RFC3339_EXTENDED',
    'RSS',
    'W3C',
] as $format) {
    eval("print 'DateTimeInterface::$format\t'.\$dateTime->format(DateTimeInterface::$format).\"\n\";");
}
  • public static createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

  • public format(string $format): string

  • public modify(string $modifier): DateTime|false

  • public add(DateInterval $interval): DateTime
  • public sub(DateInterval $interval): DateTime

  • public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval

  • public getOffset(): int

  • public getTimestamp(): int
  • public setTimestamp(int $timestamp): DateTime
  • public getTimezone(): DateTimeZone|false
  • public setTimezone(DateTimeZone $timezone): DateTime
  • public setDate(int $year, int $month, int $day): DateTime
  • public setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime
  • public setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): DateTime
$d = new DateTime('2011-01-01T15:03:01.012345Z');
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345

$d->modify('+1 month');
$d->add(new DateInterval("P1M"));

$publishDate = DateTime::createFromFormat('m/d/Y', '1/10/2014');
echo $publishDate->getTimestamp();

#1 PHP 字符串操作

2011-05-01
  1. 单引号,双引号
  2. heredoc <<<EOF ... EOF;
  3. nowdoc <<<'EOF' ... EOF; 忽略变量和转义

操作

  1. 字符串连接 $s1 . $s2
  2. echo
  3. print
int printf ( string $format , mixed ...$args )
string sprintf ( string $format , mixed ...$args )
void var_dump ( mixed $expression , mixed ...$expressions )
mixed print_r ( mixed $expression [, bool $return = false ] )
strlen(string $string): int
substr(string $string, int $start, ?int $length = null): string|false
str_replace(string|array $search, string|array $replace, string|array $subject, ?int &$count = null): string|array|null
strpos(string $haystack, string $needle, ?int $offset = 0): int|false
explode(string $delimiter, string $string, ?int $limit = PHP_INT_MAX): array
implode(string $glue, array $pieces): string
strtolower(string $string): string
strtoupper(string $string): string
ucfirst(string $string): string
ucwords(string $string, string|null $delimiters = " \t\r\n\f\v"): string
trim(string $string, ?string $charlist = " \t\n\r\0\x0B"): string
str_repeat(string $string, int $multiplier): string
htmlspecialchars(string $string, int $flags = ENT_COMPAT | ENT_HTML401, ?string $encoding = ini_get("default_charset"), bool $double_encode = true): string
strtolower(string $string): string
strtoupper(string $string): string
lcfirst(string $string): string
strrev(string $string): string
ucfirst(string $string): string
ucwords(string $string): string
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
strcmp(string $str1, string $str2): int
strcasecmp(string $str1, string $str2): int
stristr(string $haystack, string $needle, bool $before_needle = false): string|false
strstr(string $haystack, string $needle, bool $before_needle = false): string|false
strtok(string $string, string $delimiter): string|false
strpos(string $haystack, string $needle, ?int $offset = 0): int|false
strrpos(string $haystack, string $needle, ?int $offset = 0): int|false
substr_count(string $haystack, string $needle, ?int $offset = 0, ?int $length = null): int
substr_replace(string $string, string $replacement, int|array $start, ?int|array $length = null): string|array
wordwrap(string $string, ?int $width = 75, ?string $break = "\n", bool $cut = false): string
str_shuffle(string $string): string
str_split(string $string, int $split_length = 1): array
str_word_count(string $string, ?int $format = 0, ?string $charlist = ""): int|array
strcoll(string $str1, string $str2): int
strcspn(string $string, string $mask, ?int $start = 0, ?int $length = null): int
strip_tags(string $string, ?string $allowable_tags = null): string
html_entity_decode(string $string, ?int $flags = ENT_COMPAT | ENT_HTML401, ?string $encoding = ini_get("default_charset")): string
htmlentities(string $string, int $flags = ENT_COMPAT | ENT_HTML401, ?string $encoding = ini_get("default_charset"), bool $double_encode = true): string
htmlspecialchars_decode(string $string, ?int $flags = ENT_COMPAT | ENT_HTML401): string
preg_match(string $pattern, string $subject, ?array &$matches = null, ?int $flags = 0, int $offset = 0): int|false
preg_replace(mixed $pattern, mixed $replacement, mixed $subject, ?int $limit = -1, ?int &$count = null): mixed
preg_split(string $pattern, string $subject, ?int $limit = -1, ?int $flags = 0): array
substr_compare(string $main_str, string $str, int $offset, ?int $length = null, bool $case_insensitive = false): int
strcoll(string $str1, string $str2): int
strcspn(string $string, string $mask, ?int $start = 0, ?int $length = null): int
strip_tags(string $string, ?string $allowable_tags = null): string
strtr(string $string, string|array $replace_pairs): string
strval(mixed $var): string
substr_replace(string $string, string $replacement, int|array $start, ?int|array $length = null): string|array
levenshtein(string $str1, string $str2, ?int $cost_ins = 1, ?int $cost_rep = 1, ?int $cost_del = 1): int