PHP正则表达式入门教程[转],正则表达式入门教程
思维导图 点击下图,可以看具体内容!
$regex = '/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html$/i' ;
$str = 'http://www.youku.com/show_page/id_ABCDEFG.html' ;
$matches = array();
if (preg_match($regex, $str, $matches)){
var_dump($matches);
}
echo "\n" ;
|
preg_match中的$matches[0]将包含与整个模式匹配的字符串。
使用"#"定界符的代码如下.这个时候对"/"就不转义!
$regex = '#^http://([\w.]+)/([\w]+)/([\w]+)\.html$#i' ;
$str = 'http://www.youku.com/show_page/id_ABCDEFG.html' ;
$matches = array();
if (preg_match($regex, $str, $matches)){
var_dump($matches);
}
echo "\n" ;
|
¤ 修饰符:用于改变正则表达式的行为。
我们看到的('/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html/i')中的最后一个"i"就是修饰符,表示忽略大小写,还有一个我们经常用到的是"x"表示忽略空格。
贡献代码:
$regex = '/HELLO/' ;
$str = 'hello word' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
echo 'No i:Valid Successful!' , "\n" ;
}
if (preg_match( $regex . 'i' , $str , $matches )){
echo 'YES i:Valid Successful!' , "\n" ;
}
|
¤ 字符域:[\w]用方括号扩起来的部分就是字符域。
¤ 限定符:如[\w]{3,5}或者[\w]*或者[\w]+这些[\w]后面的符号都表示限定符。现介绍具体意义。
{3,5}表示3到5个字符。{3,}超过3个字符,{,5}最多5个,{3}三个字符。
* 表示0到多个
+ 表示1到多个。
¤ 脱字符号
^:
> 放在字符域(如:[^\w])中表示否定(不包括的意思)——“反向选择”
> 放在表达式之前,表示以当前这个字符开始。(/^n/i,表示以n开头)。
注意,我们经常管"\"叫"跳脱字符"。用于转义一些特殊符号,如".","/"
通配符(lookarounds):断言某些字符串中某些字符的存在与否! lookarounds分两种:lookaheads(正向预查 ?=)和lookbehinds(反向预查? 格式: 正向预查:(?=) 相对应的 (?!)表示否定意思 反向预查:(?
$regex
=
'/(?<code class="php plain">;
/* d 前面紧跟c, d 后面紧跟e*/
$str
=
'abcdefgk'
;
$matches
=
array
();
if
(preg_match(
$regex
,
$str
,
$matches
)){
var_dump(
$matches
);
}
echo
"\n"
;
否定意义:
$regex = '/(?<code class="php plain">; /* d 前面不紧跟c, d 后面不紧跟e*/
$str = 'abcdefgk' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
>字符宽度:零 验证零字符代码
$regex = '/HE(?=L)LO/i' ;
$str = 'HELLO' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
打印不出结果!
$regex = '/HE(?=L)LLO/i' ;
$str = 'HELLO' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
能打印出结果!
说明:(?=L)意思是HE后面紧跟一个L字符。但是(?=L)本身不占字符,要与(L)区分,(L)本身占一个字符。
捕获数据 没有指明类型而进行的分组,将会被获取,供以后使用。 > 指明类型指的是通配符。所以只有圆括号起始位置没有问号的才能被捕捉。 > 在同一个表达式内的引用叫做反向引用。 > 调用格式: \编号(如\1)。
$regex = '/^(Chuanshanjia)[\w\s!]+\1$/' ;
$str = 'Chuanshanjia thank Chuanshanjia' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
> 避免捕获数据 格式:(?:pattern) 优点:将使有效反向引用数量保持在最小,代码更加、清楚。 >命名捕获组 格式:(?P) 调用方式 (?P=组名)
$regex = '/(?P<author>chuanshanjia)[\s]Is[\s](?P=author)/i'</author> ;
$str = 'author:chuanshanjia Is chuanshanjia' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
运行结果
惰性匹配(记住:会进行两部操作,请看下面的原理部分)
格式:限定符?
原理:"?":如果前面有限定符,会使用最小的数据。如“*”会取0个,而“+”会取1个,如过是{3,5}会取3个。
先看下面的两个代码:
代码1.
<?php
$regex = '/heL*/i' ;
$str = 'heLLLLLLLLLLLLLLLL' ;
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
结果1.
代码2
<?php
$regex = '/heL*?/i' ;
$str = 'heLLLLLLLLLLLLLLLL' ;
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
结果2
代码3,使用“+”
<?php
$regex = '/heL+?/i' ;
$str = 'heLLLLLLLLLLLLLLLL' ;
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
结果3
代码4,使用{3,5}
<?php
$regex = '/heL{3,10}?/i' ;
$str = 'heLLLLLLLLLLLLLLLL' ;
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
结果4
$regex = '/
^host=(?
<code class="php plain">\|
([\w!@#$%^&*()_+\-]+) (?#用户名)
\|
([\w!@#$%^&*()_+\-]+) (?#密码)
(?!\|)$/ix';
$str = 'host=192.168.10.221|root|123456' ;
$matches = array ();
if (preg_match( $regex , $str , $matches )){
var_dump( $matches );
}
echo "\n" ;
|
特殊字符
特殊字符 | 解释 |
* | 0到多次 |
+ | 1到多次还可以写成{1,} |
? | 0或1次 |
. | 匹配除换行符外的所有单个的字符 |
\w | [a-zA-Z0-9_] |
\s | 空白字符(空格,换行符,回车符)[\t\n\r] |
\d | [0-9] |

phpsessionscanstorestrings, 숫자, 배열 및 객체 1.Strings : TextDatalikeUsernames.2.numbers : integorfloatsforcounters.3.arrays : listslikeshoppingcarts.4.objects : complexStructuresThatareserialized.

세션 재생은 세션 고정 공격의 경우 사용자가 민감한 작업을 수행 할 때 새 세션 ID를 생성하고 이전 ID를 무효화하는 것을 말합니다. 구현 단계에는 다음이 포함됩니다. 1. 민감한 작업 감지, 2. 새 세션 ID 생성, 3. 오래된 세션 ID 파괴, 4. 사용자 측 세션 정보 업데이트.

PHP 세션은 응용 프로그램 성능에 큰 영향을 미칩니다. 최적화 방법은 다음과 같습니다. 1. 데이터베이스를 사용하여 세션 데이터를 저장하여 응답 속도를 향상시킵니다. 2. 세션 데이터 사용을 줄이고 필요한 정보 만 저장하십시오. 3. 비 차단 세션 프로세서를 사용하여 동시성 기능을 향상시킵니다. 4. 사용자 경험과 서버 부담의 균형을 맞추기 위해 세션 만료 시간을 조정하십시오. 5. 영구 세션을 사용하여 데이터 읽기 및 쓰기 시간의 수를 줄입니다.

phpsessionsareser-side, whilecookiesareclient-side.1) sessions stessoredataontheserver, andhandlargerdata.2) cookiesstoredataonthecure, andlimitedinsize.usesessionsforsensitivestataondcookiesfornon-sensistive, client-sensation.

phpidifiesauser의 sssessionusessessioncookiesandssessionids.1) whensession_start () iscalled, phpgeneratesauniquessessionStoredInacookienamedPhpsSessIdonSeuser 'sbrowser.2) thisidallowsphptoretrievessessionDataTromServer.

PHP 세션의 보안은 다음 측정을 통해 달성 할 수 있습니다. 1. Session_REGENEREAT_ID ()를 사용하여 사용자가 로그인하거나 중요한 작업 일 때 세션 ID를 재생합니다. 2. HTTPS 프로토콜을 통해 전송 세션 ID를 암호화합니다. 3. 세션 _save_path ()를 사용하여 세션 데이터를 저장하고 권한을 올바르게 설정할 보안 디렉토리를 지정하십시오.

phpsessionfilesarestoredInTheRectorySpecifiedBysession.save_path, 일반적으로/tmponunix-likesystemsorc : \ windows \ temponwindows.tocustomizethis : 1) austession_save_path () toSetacustomDirectory, verlyTeCustory-swritation;


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Dreamweaver Mac版
시각적 웹 개발 도구
