search
HomeBackend DevelopmentPHP Tutorial八、字符串的相关操作

PHP常用字符串函数小结

一、判断类型的函数

is_bool()       //判断是否为布尔型is_float()      //判断是否为浮点型is_real()       //同上is_int()        //判断是否为整型is_integer()    //同上is_string()     //判断是否为字符串is_object()     //判断是否为对象is_array()      //判断是否为数组is_null()       //判断是否为nullis_file()       //判断是否为文件is_dir()        //判断是否为目录is_numeric()    //判断是否为数字is_nan()        //判断不是数字is_resource()   //判断是否为资源类型is_a($obj,$classname) //判断对象是否为类的实例                      //可用 if($obj instanceof Classname)

二、获取子串位置

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 中最后一次出现的数字位置,不区分大小写。 

三、获取子串

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");	}

四、字符串str_ 型函数

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

五、字符串长度

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

六、翻转字符串

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

七、mb_类型字符串函数

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

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

$encode = mb_detect_encoding($lines, array("ASCII","UTF-8","GB2312","GBK","BIG5"));if($encode != "UTF-8"){    $lines = iconv($encode,"UTF-8", $lines);}

八、字符串的相关操作

1、转换字符串类型

strval($str); //转换成字符串类型floatval($str);//转换成浮点型intval($str); //转换成整型

2、大小写转换

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

3、字符串转时间戳

strtotime($str); //时间格式的字符串转换成整型时间戳           //注意设置时区 否则会有 8小时误差

4、去除HTML 和 PHP 标记

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

5、ascii转数字 数字转ascii

chr(int $ascii); //数字转换成asciiord(string $str); //返回$str第一个字符的ascii值

6、json的编码与解码

json_encode($obj/$arr/$str...);//编码成json 格式的字符串json_decode($jsonstr [,$assoc=true]); //解码成对象                         //当$assoc=true 时 返回数组 而非对象

7、换行转

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

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

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

9、千位分割格式化

string number_format ( float $number [, int $decimals = 0 ] )string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' ) @param   $number 你要格式化的数字           $decimals 要保留的小数位数           $dec_point 指定小数点显示的字符           $thousands_sep 指定千位分隔符显示的字符 

10、去空格

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

该函数删除 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、转换字符串编码函数

iconv($in_charset, $out_charset, $str);$in_charset输入字符集$out_charset输出字符集

12、字符串加密函数

sha1($str); md5($str);

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

addcslashes(string $str , string $charlist);//转义字符串中的特殊字符               //eg. addcslashes($str,"\0..\37!@\177..\377");			   //转义ascii [email protected]stripcslashes($str) — 反转义addcslashes()函数转义处理过的字符串  返回反转义后的字符串。可识别类似 C 语言的 \n,\r,... 八进制以及十六进制的描述

14、按格式返回数据

sprintf — 按照要求对数据进行返回,但是不输出	可表示类型如下:	string s 	integer d, u, c, o, x, X, b  	double g, G, e, E, f, F  	eg.	$num = 5;	$location = 'tree';	$format = 'There are %d monkeys in the %s';	echo sprintf($format, $num, $location);





Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools