Home Backend Development PHP Tutorial Summary of commonly used string functions in PHP (recommended)

Summary of commonly used string functions in PHP (recommended)

Oct 08, 2018 pm 04:09 PM
php string functions

这篇文章主要介绍了PHP常用字符串函数小结,这篇文章整理的比较详细与明了需要的朋友根据参数搜索具体的使用教程

一、判断类型的函数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

is_bool()    //判断是否为布尔型

is_float()   //判断是否为浮点型

is_real()    //同上

is_int()    //判断是否为整型

is_integer()  //同上

is_string()   //判断是否为字符串

is_object()   //判断是否为对象

is_array()   //判断是否为数组

is_null()    //判断是否为null

is_file()    //判断是否为文件

is_dir()    //判断是否为目录

is_numeric()  //判断是否为数字

is_nan()    //判断不是数字

is_resource()  //判断是否为资源类型

is_a($obj,$classname) //判断对象是否为类的实例

           //可用 if($obj instanceof Classname)

Copy after login

二、获取子串位置

1

2

3

4

strpos($hs,$nd [,int $offset = 0 ]) //返回nd 在 hs 中首次出现的数字位置。

stripos($hs,$nd [,int $offset = 0 ]) //返回nd 在 hs 中首次出现的数字位置, 不区分大小写。

strrpos($hs,$nd [,int $offset = 0 ]) //返回nd 在 hs 中最后一次出现的数字位置。

strripos($hs,$nd [,int $offset = 0 ]) //返回nd 在 hs 中最后一次出现的数字位置,不区分大小写。

Copy after login

三、获取子串

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

substr($str,$start [,$length]); //获取子串

substr_compare($main_str,$str,$offset[,$length]); //子串比较 从offset处开始比较

substr_count($hs,$nd [,$offset=0 [,$length]]); //获取子串nd在hs中出现的次数

substr_replace($string,$replacement,$start [,$length]); //字符串子串替换

                //用$replacement替换掉$string从start开始长度为length的子串

strstr($hys,$nd [,bool $before_needle = false ]);//返回$nd在$hys 第一次出现的地方开始到字符串结束 为止的字符串

        //第三个参数如果为true 则返回$nd 之前的字符串

stristr($hys,$nd [,bool $before_needle = false ]); //同上,忽略大小写版本

strrchr($hys,$nd); //返回$nd在$hys最后一次出现的地方开始到字符串结束 为止的字符串

        //一般和 substr(strrchr($hys,$nd),strlen($nd)); 合用

strpbrk($haystack,$char_list);//从$char_list中依次匹配单个字符在$haystack中第一次出现的地方

            //到字符串结束的地方 的整个字符串

strtok($str,$token); //第一次使用 将字符串按分隔符$token进行分割

strtok($token);   //第二次使用

    eg.

    $string = "This is\tan example\nstring";

    /* 使用制表符和换行符作为分界符 */

    $tok = strtok($string, " \n\t");

  

    while ($tok !== false) {

        echo "Word=$tok<br />";

        $tok = strtok(" \n\t");

    }

Copy after login

四、字符串str_ 型函数

1

2

3

4

5

6

7

8

str_getcsv($str); //将csv文件字符串转换成一个数组

str_replace($search,$replace,$subject [,&$count]);//搜索并替换字符串

      //第四个参数被指定的话,将会赋值给他替换的次数

str_ireplace($search,$replace,$subject [,&$count]);//搜索并替换字符串

      //第四个参数被指定的话,将会赋值给他替换的次数 忽略大小写

str_shuffle(string $str);//随机打乱字符串

str_split($str [,$len=1]);//将字符串转换成一个数组

             //,每个数组单元的长度为$len

Copy after login

五、字符串长度

strlen($str); //字符串长度

六、翻转字符串

strrev(string $string);// 翻转字符串

七、mb_类型字符串函数

mb_类型字符串与上述字符串函数基本一样,
只是加多一个可选的字符编码参数,用法同上
这里列出一些其他有用函数

1、检测字符串的字符编码

1

2

3

4

$encode = mb_detect_encoding($lines, array("ASCII","UTF-8","GB2312","GBK","BIG5"));

if($encode != "UTF-8"){

  $lines = iconv($encode,"UTF-8", $lines);

}

Copy after login

八、字符串的相关操作

1、转换字符串类型

1

2

3

strval($str); //转换成字符串类型

floatval($str);//转换成浮点型

intval($str); //转换成整型

Copy after login

2、大小写转换

1

2

strtolower($str); //全部转换成小写

strtoupper($str); //全部转换成大写

Copy after login

3、字符串转时间戳

1

2

strtotime($str); //时间格式的字符串转换成整型时间戳

      //注意设置时区 否则会有 8小时误差

Copy after login

4、去除HTML 和 PHP 标记

1

strip_tags($str [,$tags]);//去除不含$tags里标签外的所有标签

Copy after login

5、ascii转数字 数字转ascii

1

2

chr(int $ascii); //数字转换成ascii

ord(string $str); //返回$str第一个字符的ascii值

Copy after login

6、json的编码与解码

1

2

3

json_encode($obj/$arr/$str...);//编码成json 格式的字符串

json_decode($jsonstr [,$assoc=true]); //解码成对象

             //当$assoc=true 时 返回数组 而非对象

Copy after login

7、换行转

1

nl2br($str); //字符串 $str 所有新行之前插入&#39;<br/>&#39;

Copy after login

8、数组转字符串,字符串转数组

1

2

implode($arr,$glue);//将一维数组转换为字符串

explode();//字符串转换为数组

Copy after login

9、千位分割格式化

1

2

3

4

5

6

string number_format ( float $number [, int $decimals = 0 ] )

string number_format ( float $number , int $decimals = 0 , string $dec_point = &#39;.&#39; , string $thousands_sep = &#39;,&#39; )

 @param  $number 你要格式化的数字

     $decimals 要保留的小数位数

     $dec_point 指定小数点显示的字符

     $thousands_sep 指定千位分隔符显示的字符

Copy after login

10、去空格

1

2

3

trim(string $str [,string $charlist ]); //去左右字符

ltrim(string $str [,string $charlist ]); //去左字符

rtrim(string $str [,string $charlist ]); //去右字符

Copy after login

该函数删除 str 末端的空白字符并返回。

不使用第二个参数, rtrim() 仅删除以下字符:
• " " (ASCII 32 (0x20)),普通空白符。
• "\t" (ASCII 9 (0x09)),制表符。
• "\n" (ASCII 10 (0x0A)),换行符。
• "\r" (ASCII 13 (0x0D)),回车符。
• "\0" (ASCII 0 (0x00)),NUL 空字节符。
• "\x0B" (ASCII 11 (0x0B)),垂直制表符。
过滤字符也可由 charlist 参数指定。一般要列出所有希望过滤的字符,
也可以使用 ".." 列出一个字符范围

11、转换字符串编码函数

1

2

3

iconv($in_charset, $out_charset, $str);

$in_charset输入字符集

$out_charset输出字符集

Copy after login

12、字符串加密函数

1

2

sha1($str);

md5($str);

Copy after login

13、字符串转义与反转义函数

1

2

3

4

5

6

addcslashes(string $str , string $charlist);//转义字符串中的特殊字符

        //eg. addcslashes($str,"\0..\37!@\177..\377");

              //转义ascii 中0-37、177-377中不含@符号的字符

  

stripcslashes($str) — 反转义addcslashes()函数转义处理过的字符串

 返回反转义后的字符串。可识别类似 C 语言的 \n,\r,... 八进制以及十六进制的描述

Copy after login

14、按格式返回数据

1

2

3

4

5

6

7

8

9

10

sprintf — 按照要求对数据进行返回,但是不输出

    可表示类型如下:

    string s

    integer d, u, c, o, x, X, b

    double g, G, e, E, f, F

    eg.

    $num = 5;

    $location = &#39;tree&#39;;

    $format = &#39;There are %d monkeys in the %s&#39;;

    echo sprintf($format, $num, $location);

Copy after login

这篇关于php常用字符串函数的文章就介绍到这了,更多相关教程请访问php编程从入门到精通全套视频教程

The above is the detailed content of Summary of commonly used string functions in PHP (recommended). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

See all articles