Home > Backend Development > PHP Problem > Recommend 9 commonly used php codes (remember to collect them)

Recommend 9 commonly used php codes (remember to collect them)

醉折花枝作酒筹
Release: 2023-03-11 18:02:02
forward
4895 people have browsed it

收集一些日常开发中一些有用的PHP代码段,会持续更新。今天就向大家介绍一下,有需要的小伙伴可以参考参考。

Recommend 9 commonly used php codes (remember to collect them)

收集一些日常开发中一些有用的PHP代码段,会持续更新。
如果代码有BUG或者任何建议,欢迎在评论区评论!

1、把一个数字限定在某个范围内,比如要限定$a在区间[1, 12]内,当$a=17时,就令$a=12:

min(max($a, 1), 12);
Copy after login

2、检查一个日期是不是有效,比如非闰年时给了个2月29日:

$date = '2016-2-29';
list($year, $month, $day) = explode('-', $date);
echo checkdate($month, $day, $year) ? 'yes' : 'no';
Copy after login

3、下划线风格的字符串转驼峰风格:

$a = 'long_under_line_name';
echo lcfirst(str_replace('_', '', ucwords($a, '_')));
Copy after login

4、驼峰风格字符串转下划线风格:

$a = 'longCamelCaseName';
echo strtolower(preg_replace('/[A-Z]/', '_$0', $a));
Copy after login

5、连接MySQL并查询数据:

$link = new mysqli('127.0.0.1', '用户名', '密码', '数据库名');
$link->query('SET NAMES utf8');
$rs = $link->query('SELECT * FROM table');
while ($row = $rs->fetch_assoc()) {
    // $row为查出的每一行
}
$link->close();
Copy after login

6、获得客户端IP

echo $_SERVER['REMOTE_ADDR'];
Copy after login

7、一万亿以内数字转中文串:

  $dict = ['零', '一','二','三','四','五','六','七','八','九','十','百','千','万','亿'];
  $num = 1234567890;
  $string = strrev($num);

  $text = '';
  for ($i = 0; $i !== 12; $i += 4) {
      $s = substr($string, $i, 4);
      $t = '';
      for ($j = 0; $j != 4; $j++) {
          if (!isset($s[$j])) continue;
          $u = $j && $s[$j] ? $dict[9 + $j] : '';
          $t = (($t || $s[$j]) && ($s[$j] !== '1' || $j !== 1) ? $dict[$s[$j]] : '') . $u . $t;
      }
      if ($t) {
          $text = preg_replace('/零+/u', '零', $t) . ($i ? $dict[12+$i/4]: '') . $text;
      }
  }

  echo $text . PHP_EOL;
Copy after login

8、字符串”true”, “false”转bool值
注意,如果直接用(bool) "false"转的话会返回true,任何非空字符串都会被转成true

$str = 'false';
$bool = filter_var($str, FILTER_VALIDATE_BOOLEAN);
Copy after login

9、如果获得PHP当前运行操作系统的信息

// 两种方式
echo php_uname();
// Windows 输出 Windows NT PC115080 6.1 build 7601 (Windows 7 Professional Edition Service Pack 1) AMD64
// Linux 输出 Linux VM_238_239_centos 3.10.0-514.21.1.el7.x86_64 #1 SMP Thu May 25 17:04:51 UTC 2017 x86_64

echo PHP_OS;
// Windows 输出 WINNT
// Linux 输出 Linux
Copy after login

推荐学习:php视频教程

The above is the detailed content of Recommend 9 commonly used php codes (remember to collect them). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template