Table of Contents
php中字符串和正则表达式详解,php正则表达式详解
PHP 正则表达式+字符串提取问题
PHP中怎用正则表达式给一段字符串内加内容?
Home php教程 php手册 php中字符串和正则表达式详解,php正则表达式详解

php中字符串和正则表达式详解,php正则表达式详解

Jun 13, 2016 am 09:23 AM
php string regular expression

php中字符串和正则表达式详解,php正则表达式详解

一、字符串类型的特点

1、PHP是弱类型语言,其他数据类型一般都可以直接应用于字符串函数操作。

1

echo substr("123456",2,4);  //输出345<br>echo substr(123456,2,4);    //输出345<br>echo hello;                 //先查找hello常量,若没找到,将hello看做字符串使用<br>?>

Copy after login

2、字符串可以作为“数组”,是字符的集合。

1

$str = "www.jb51.net";<br>echo $str[0];<br>echo $str[1];<br>echo $str[2];<br>?>

Copy after login

但是字符串不是真的数组,不能使用数组的函数.如count($str)不会返回字符串长度。PHP引擎无法区分字符和数组,产生二义性。自PHP4起,已经用花括号替代方括号。

1

//为保证向后兼容,方括号仍然可以使用<br>$str = www.jb51.net;<br>echo $str{0};<br>echo $str{1};<br>echo $str{2};<br>?>

Copy after login

3、双引号变量解析

在PHP中,当用双引号或者定界符定义字符串时,其中的变量会被解析。

1

$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>?>

Copy after login

二、字符串输出函数

三、常用的字符串格式函数

PS:PHP的字符串处理函数大部分不对源字符串做修改,而是返回新的字符串

四、正则表达式

正则表达式描述了一种字符串匹配的模式,通过这个模式在特定的函数中对字符串进行匹配、查找、替换和分隔等操作,由原子、元字符和模式修正符三部分组成的文字模式。

在PHP中,有两套正则的处理函数库:PCRE和POSIX。前者以preg_前缀命名,与Perl兼容;后者以ereg_前缀命名。二者功能相似,但PCRE的效率略高。

与Perl语言兼容的正则表达式处理函数:

1、语法

1.1 定界符:在与Perl兼容的正则函数中使用模式时,必须给模式加上定界符。除了字母、数字和反斜线(\)之外的任何字符都可以作为定界符号

1

//以下正则合法<br>echo $m1 = '/echo $m2 = '|(\d{3})-\d|Sm';<br>echo $m3 = '!^(?i)php[34]!';<br>echo $m4 = '{^\s+(\s+)?$}';<br>?>

Copy after login

1.2 原子:原子包含了普通字符,如字母、数字;非打印字符,如空格、回车;特殊字符和元字符,如引号、*、+等,必须用”\”进行转义;自定义原子表,如[apj]、[a-z];通用字符类型,如\d、\D。

1

//下面二者等价,匹配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>?>

Copy after login

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中第一个小括号中匹配的内容,以此类推。

1

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>?>

Copy after login

结果

preg_match_all()与preg_match()函数类似,不同的是前者会一直匹配到字符串末尾,后者在第一次匹配后就停止匹配。

2.2 preg_grep(string pattern,array iput):匹配数组中的元素,返回与正则匹配的数组单元。参数说明:

pattern是正则,input是需要匹配的数组。

1

$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>?>

Copy after login

2.3 preg_replace(mixed pattern,mixed replacement,mixed subject[,int limit]):字符串替换。说明:

该函数会在subject中搜索与pattern的匹配项,并用replacement替换。limit用于限制匹配的次数,即替换的次数。

1

$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>?>

Copy after login

2.4 preg_split(string pattern,string subject[,int limit[,int flags]]):对字符串进行分割。说明:

函数返回一个数组。数组元素包含subject中与pattern匹配作为边界所分割的字符串,limit含义见2.3,flags含义请参考文档。

1

//按任数量的空格分割字符串<br>$kerwords = preg_split("/[\s,]+/","hypertext language,programming");<br>//输出:Array([0]=>hypertext [1]=>language,[2[=>programming)<br>print_r($kerwords);<br>?>

Copy after login

PHP 正则表达式+字符串提取问题


$str='{"a":1234567890,"b":"u","birthday":"2000-01-01","gender":"1","location":"123456","login_ip":"123.123.123.123","login_time":1234567890,"id":"1234567","sign":"0bcbdea54d1f2c3c75b058eb5d2ae124"}';
$user_id="";
if (preg_match_all('|"id":"(\S+?)"|', $str, $reg))
{
$user_id=$reg[1][0];
}
echo "UserID is : ".$user_id;
?>

输出结果:
UserID is : 1234567
 

PHP中怎用正则表达式给一段字符串内加内容?

可以用正则表达式,也可以直接用php,感觉还是php比较方便一点:
$str = str_replace("","",$str);
 

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles