php中字符串和正则表达式详解_php实例
一、字符串类型的特点
1、PHP是弱类型语言,其他数据类型一般都可以直接应用于字符串函数操作。
echo substr("123456",2,4); //输出345<br>echo substr(123456,2,4); //输出345<br>echo hello; //先查找hello常量,若没找到,将hello看做字符串使用<br>?>
2、字符串可以作为“数组”,是字符的集合。
$str = "www.php.net";<br>echo $str[0];<br>echo $str[1];<br>echo $str[2];<br>?>
但是字符串不是真的数组,不能使用数组的函数.如count($str)不会返回字符串长度。PHP引擎无法区分字符和数组,产生二义性。自PHP4起,已经用花括号替代方括号。
//为保证向后兼容,方括号仍然可以使用<br>$str = www.php.net;<br>echo $str{0};<br>echo $str{1};<br>echo $str{2};<br>?>
3、双引号变量解析
在PHP中,当用双引号或者定界符定义字符串时,其中的变量会被解析。
$arr = array('name' => "dwqs",'add' => "www.ido321.com");<br>echo "$arr[name]"; //可以解析,但是在方括号中不能使用引号<br>//echo "$arr['name']"; 错误<br>echo "{$arr['name']}"; //可以解析,用花括号包含元素,name不带引号也是可以的<br>//假设存在对象$square<br>echo "$square->width"; //可以解析<br>echo "$square->width00 cent"; //不可以解析,用花括号解决<br>echo "{$square->width}width00 cent"; //可以解析<br>?>
二、字符串输出函数
三、常用的字符串格式函数
PS:PHP的字符串处理函数大部分不对源字符串做修改,而是返回新的字符串
四、正则表达式
正则表达式描述了一种字符串匹配的模式,通过这个模式在特定的函数中对字符串进行匹配、查找、替换和分隔等操作,由原子、元字符和模式修正符三部分组成的文字模式。
在PHP中,有两套正则的处理函数库:PCRE和POSIX。前者以preg_前缀命名,与Perl兼容;后者以ereg_前缀命名。二者功能相似,但PCRE的效率略高。
与Perl语言兼容的正则表达式处理函数:
1、语法
1.1 定界符:在与Perl兼容的正则函数中使用模式时,必须给模式加上定界符。除了字母、数字和反斜线(\)之外的任何字符都可以作为定界符号
//以下正则合法<br>echo $m1 = '/echo $m2 = '|(\d{3})-\d|Sm';<br>echo $m3 = '!^(?i)php[34]!';<br>echo $m4 = '{^\s+(\s+)?$}';<br>?>
1.2 原子:原子包含了普通字符,如字母、数字;非打印字符,如空格、回车;特殊字符和元字符,如引号、*、+等,必须用”\”进行转义;自定义原子表,如[apj]、[a-z];通用字符类型,如\d、\D。
//下面二者等价,匹配e-mail<br>$mail1 = '/^[0-9a-zA-Z]+@[0-9a-zA-Z]+(\.[0-9a-zA-Z]+){0,3}$/';<br>$mail2 = '/^\w+@\w+(\.\w+){0,3}$/';<br>?>
1.3 元字符:用于构建正则表达式的具有特殊含义的字符。Perl可以使用各种元字符来搜索匹配,如*、+、?.常见的元字符如下
1.4 模式修正符:在正则的定界符之外使用,扩展正则在匹配、替换等方面的功能。
2.与Perl兼容的正则表达式函数
2.1 preg_match(string pattern,string subject[,array matches]):用于对字符串的查找和匹配。参数说明:
pattern是正则,subject是需要处理的字符串,可选的matches用于保存于pattern的各个子模式的匹配结果,matches[0]保存了与pattern匹配的整体内容,matches[1]保存了pattern中第一个小括号中匹配的内容,以此类推。
header("content-type:text/html;charset=utf8");<br>$pattern = '/(http):\/\/(www)\.([^\.\/]+)\.(com|net|org)/i';<br>$subject = "我的博客:http://www.ido321.com";<br>if(preg_match($pattern, $subject,$matches)){<br>echo "搜索的URL是:".$matches[0]."<br>"; //数组第1个元素保存整个匹配结果<br>echo "URL中的协议是:".$matches[1]."<br>";//数组第2个元素保存第1个字表达式<br>echo "URL中的主机是:".$matches[2]."<br>";//数组第3个元素保存第2个字表达式<br>echo "URL中的域名是:".$matches[3]."<br>";//数组第4个元素保存第3个字表达式<br>echo "URL中的顶域是:".$matches[4]."<br>";//数组第5个元素保存第4个字表达式<br>}<br>?>
结果
preg_match_all()与preg_match()函数类似,不同的是前者会一直匹配到字符串末尾,后者在第一次匹配后就停止匹配。
2.2 preg_grep(string pattern,array iput):匹配数组中的元素,返回与正则匹配的数组单元。参数说明:
pattern是正则,input是需要匹配的数组。
$arr = array('Linux RedHat9.0','Apache2.2.9','MySQL5.0.51','PHP5.2.6','LAMP','100');<br>$version = preg_grep('/^[a-zA-Z]+(\d|\.)+$/',$arr);<br>//输出:Array([1]=>Apache2.2.9 [2]=>MySQL5.0.51 [3]=>PHP5.2.6)<br>print_r($version); <br>?>
2.3 preg_replace(mixed pattern,mixed replacement,mixed subject[,int limit]):字符串替换。说明:
该函数会在subject中搜索与pattern的匹配项,并用replacement替换。limit用于限制匹配的次数,即替换的次数。
$pattern = '/]*?/is';<br>$text = '这个文本有<b>粗体</b>和<u>带有下划线</u>以及<i>斜体</i>';<br>echo preg_replace($pattern,"",$text); //将所有HTML标记替换为空<br>echo preg_replace($pattern,"",$text,2); //值替换前2个HTML标记<br>?>
2.4 preg_split(string pattern,string subject[,int limit[,int flags]]):对字符串进行分割。说明:
函数返回一个数组。数组元素包含subject中与pattern匹配作为边界所分割的字符串,limit含义见2.3,flags含义请参考文档。
//按任数量的空格分割字符串<br>$kerwords = preg_split("/[\s,]+/","hypertext language,programming");<br>//输出:Array([0]=>hypertext [1]=>language,[2[=>programming)<br>print_r($kerwords);<br>?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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.

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

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

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.
