search
HomeBackend DevelopmentPHP Tutorial15 Practical PHP Regular Expressions_PHP Tutorial

15 个实用的 PHP 正则表达式

对于开发人员来说,正则表达式是一个非常有用的功能,它提供了 查找,匹配,替换 句子,单词,或者其他格式的字符串。这篇文章主要介绍了15个超实用的php正则表达式,需要的朋友可以参考下。在这篇文章里,我已经编写了15个超有用 的正则表达式,WEB开发人员都应该将它收藏到自己的工具包。

验证域名检验一个字符串是否是个有效域名

<ol class="dp-j"><li class="alt"><span><span>$url = </span><span class="string">"http://komunitasweb.com/"</span><span>; </span></span></li><li><span><span class="keyword">if</span><span> (preg_match(</span><span class="string">'/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i'</span><span>, $url)) { </span></span></li><li class="alt"><span>  echo <span class="string">"Your url is ok."</span><span>; </span></span></li><li><span>} <span class="keyword">else</span><span> { </span></span></li><li class="alt"><span>  echo <span class="string">"Wrong url."</span><span>; </span></span></li><li><span>} </span></li></ol>

从一个字符串中 突出某个单词

这是一个非常有用的在一个字符串中匹配出某个单词 并且突出它,非常有效的搜索结果

<ol class="dp-j"><li class="alt"><span><span>$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or  </span></span></li><li><span> </span></li><li class="alt"><span>regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";  </span></li><li><span>$text = preg_replace(<span class="string">"/b(regex)b/i"</span><span>, </span><span class="string">'<span style="background:#5fc9f6">1</span>'</span><span>, $text);  </span></span></li><li class="alt"><span>echo $text; </span></li></ol>

突出查询结果在你的 WordPress 博客里就像刚才我说的,上面的那段代码可以很方便的搜索出结果,而这里是一个更好的方式去执行搜索在某个WordPress的博客上打开你的文件 search.php ,然后找到 方法 the_title() 然后用下面代码替换掉它

<ol class="dp-j"><li class="alt"><span><span>echo $title;  </span></span></li><li><span> </span></li><li class="alt"><span>Now, just before the modified line, add <span class="keyword">this</span><span> code:  </span></span></li><li><span> </span></li><li class="alt"><span><php  </span></li><li><span>  $title   = get_the_title();  </span></li><li class="alt"><span>  $keys= explode(<span class="string">" "</span><span>,$s);  </span></span></li><li><span>  $title   = preg_replace(<span class="string">'/('</span><span>.implode(</span><span class="string">'|'</span><span>, $keys) .</span><span class="string">')/iu'</span><span>,  </span></span></li><li class="alt"><span>    <span class="string">'<strong>\0</strong>'</span><span>,  </span></span></li><li><span>    $title);  </span></li><li class="alt"><span>>  </span></li><li><span> </span></li><li class="alt"><span>Save the search.php file and open style.css. Append the following line to it:  </span></li><li><span> </span></li><li class="alt"><span>strong.search-excerpt { background: yellow; } <br /></span></li></ol>

从HTML文档中获得全部图片

如果你曾经希望去获得某个网页上的全部图片,这段代码就是你需要的,你可以轻松的建立一个图片下载机器人

<ol class="dp-j"><li class="alt"><span><span>$images = array(); </span></span></li><li><span>preg_match_all(<span class="string">'/(img|src)=("|'</span><span>)[^"</span><span class="string">'>]+/i'</span><span>, $data, $media); </span></span></li><li class="alt"><span>unset($data); </span></li><li><span>$data=preg_replace(<span class="string">'/(img|src)("|'</span><span>|="|=</span><span class="string">')(.*)/i'</span><span>,</span><span class="string">"$3"</span><span>,$media[</span><span class="number">0</span><span>]); </span></span></li><li class="alt"><span>foreach($data as $url) </span></li><li><span>{ </span></li><li class="alt"><span>  $info = pathinfo($url); </span></li><li><span>  <span class="keyword">if</span><span> (isset($info[</span><span class="string">'extension'</span><span>])) </span></span></li><li class="alt"><span>  { </span></li><li><span>    <span class="keyword">if</span><span> (($info[</span><span class="string">'extension'</span><span>] == </span><span class="string">'jpg'</span><span>) || </span></span></li><li class="alt"><span>    ($info[<span class="string">'extension'</span><span>] == </span><span class="string">'jpeg'</span><span>) || </span></span></li><li><span>    ($info[<span class="string">'extension'</span><span>] == </span><span class="string">'gif'</span><span>) || </span></span></li><li class="alt"><span>    ($info[<span class="string">'extension'</span><span>] == </span><span class="string">'png'</span><span>)) </span></span></li><li><span>    array_push($images, $url); </span></li><li class="alt"><span>  } </span></li><li><span>} </span></li></ol>

删除重复字母

经常重复输入字母? 这个表达式正适合.

<ol class="dp-j"><li class="alt"><span><span>$text = preg_replace(</span><span class="string">"/s(w+s)1/i"</span><span>, </span><span class="string">"$1"</span><span>, $text); </span></span></li></ol>

删除重复的标点

功能同上,但只是面对标点,白白重复的逗号

<ol class="dp-j"><li class="alt"><span><span>$text = preg_replace(</span><span class="string">"/.+/i"</span><span>, </span><span class="string">"."</span><span>, $text); </span></span></li></ol>

匹配一个XML或者HTML标签

这个简单的函数有两个参数:第一个是你要匹配的标签,第二个是包含XML或HTML的变量,再强调下,这个真的很强大

<ol class="dp-j"><li class="alt"><span><span>function get_tag( $tag, $xml ) { </span></span></li><li><span>$tag = preg_quote($tag); </span></li><li class="alt"><span>preg_match_all(<span class="string">'{<'</span><span>.$tag.</span><span class="string">'[^>]*>(.*?)</'</span><span>.$tag.</span><span class="string">'>.'</span><span>}', </span></span></li><li><span>          $xml, </span></li><li class="alt"><span>          $matches, </span></li><li><span>          PREG_PATTERN_ORDER); </span></li><li class="alt"><span> </span></li><li><span><span class="keyword">return</span><span> $matches[</span><span class="number">1</span><span>]; </span></span></li><li class="alt"><span>} </span></li></ol>

匹配具有属性值的XML或者HTML标签

这个功能和上面的非常相似,但是它允许你匹配的标签内部有属性值,例如你可以轻松匹配

<ol class="dp-j"><li class="alt"><span><span>function get_tag( $attr, $value, $xml, $tag=</span><span class="keyword">null</span><span> ) { </span></span></li><li><span><span class="keyword">if</span><span>( is_null($tag) ) </span></span></li><li class="alt"><span>  $tag = <span class="string">'\w+'</span><span>; </span></span></li><li><span><span class="keyword">else</span><span> </span></span></li><li class="alt"><span>  $tag = preg_quote($tag); </span></li><li><span> </span></li><li class="alt"><span>$attr = preg_quote($attr); </span></li><li><span>$value = preg_quote($value); </span></li><li class="alt"><span> </span></li><li><span>$tag_regex = <span class="string">"/<("</span><span>.$tag.</span><span class="string">")[^>]*$attr\s*=\s*"</span><span>. </span></span></li><li class="alt"><span>        <span class="string">"(['\"])$value\\2[^>]*>(.*?)<\/\\1>/"</span><span> </span></span></li><li><span> </span></li><li class="alt"><span>preg_match_all($tag_regex, </span></li><li><span>         $xml, </span></li><li class="alt"><span>         $matches, </span></li><li><span>         PREG_PATTERN_ORDER); </span></li><li class="alt"><span> </span></li><li><span><span class="keyword">return</span><span> $matches[</span><span class="number">3</span><span>]; </span></span></li><li class="alt"><span>} </span></li></ol>

匹配十六进制颜色值

web开发者的另一个有趣的工具,它允许你匹配和验证十六进制颜色值.

<ol class="dp-j"><li class="alt"><span><span>$string = </span><span class="string">"#555555"</span><span>; </span></span></li><li><span><span class="keyword">if</span><span> (preg_match(</span><span class="string">'/^#(?:(?:[a-fd]{3}){1,2})$/i'</span><span>, $string)) { </span></span></li><li class="alt"><span>echo <span class="string">"example 6 successful."</span><span>; </span></span></li><li><span>} </span></li></ol>

查找页面 title

这段代码方便查找和打印 网页

之间的内容

<ol class="dp-j"><li class="alt"><span><span>$fp = fopen(</span><span class="string">"http://www.catswhocode.com/blog"</span><span>,</span><span class="string">"r"</span><span>); </span></span></li><li><span><span class="keyword">while</span><span> (!feof($fp) ){ </span></span></li><li class="alt"><span>  $page .= fgets($fp, <span class="number">4096</span><span>); </span></span></li><li><span>} </span></li><li class="alt"><span> </span></li><li><span>$titre = eregi(<span class="string">"<title>(.*)</title>"</span><span>,$page,$regs); </span></span></li><li class="alt"><span>echo $regs[<span class="number">1</span><span>]; </span></span></li><li><span>fclose($fp); </span></li></ol>

解释 Apache 日志

大多数网站使用的都是著名的Apache服务器,如果你的网站也是,那么使用PHP正则表达式解析 apache 服务器日志 怎么样?

<ol class="dp-j"><li class="alt"><span><span class="comment">//Logs: Apache web server</span><span> </span></span></li><li><span><span class="comment">//Successful hits to HTML files only. Useful for counting the number of page views.</span><span> </span></span></li><li class="alt"><span><span class="string">'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?.html?)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'</span><span> </span></span></li><li><span> </span></li><li class="alt"><span><span class="comment">//Logs: Apache web server</span><span> </span></span></li><li><span><span class="comment">//404 errors only</span><span> </span></span></li><li class="alt"><span><span class="string">'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)404s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'</span><span> </span></span></li></ol>

使用智能引号代替双引号

如果你是一个印刷爱好者,你将喜欢这个允许用智能引号代替双引号的正则表达式,这个正则被WORDPRESS在其内容上使用

<ol class="dp-j"><li class="alt"><span><span>preg_replace(</span><span class="string">'B"b([^"x84x93x94rn]+)b"B'</span><span>, </span><span class="string">'?1?'</span><span>, $text); </span></span></li></ol>

检验密码的复杂度

这个正则表达式将检测输入的内容是否包含6个或更多字母,数字,下划线和连字符. 输入必须包含至少一个大写字母,一个小写字母和一个数字

'A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z'

WordPress: 使用正则获得帖子上的图片

我知道很多人是WORDPRESS的使用者,你可能会喜欢并且愿意使用 那些从帖子的内容检索下来的图像代码。使用这个代码在你的BLOG只需要复制下面代码到你的某个文件里

<ol class="dp-j"><li class="alt"><span><span><php </span><span class="keyword">if</span><span> (have_posts()) : ?> </span></span></li><li><span><php <span class="keyword">while</span><span> (have_posts()) : the_post(); ?> </span></span></li><li class="alt"><span> </span></li><li><span><php </span></li><li class="alt"><span>$szPostContent = $post->post_content; </span></li><li><span>$szSearchPattern = <span class="string">'~<img  src="/static/imghwm/default1.png"  data-src="smileys/souriant.png"  class="lazy"  [^ alt="15 Practical PHP Regular Expressions_PHP Tutorial" >]* />~'</span><span>; </span></span></li><li class="alt"><span> </span></li><li><span><span class="comment">// Run preg_match_all to grab all the images and save the results in $aPics</span><span> </span></span></li><li class="alt"><span>preg_match_all( $szSearchPattern, $szPostContent, $aPics ); </span></li><li><span> </span></li><li class="alt"><span><span class="comment">// Check to see if we have at least 1 image</span><span> </span></span></li><li><span>$iNumberOfPics = count($aPics[<span class="number">0</span><span>]); </span></span></li><li class="alt"><span> </span></li><li><span><span class="keyword">if</span><span> ( $iNumberOfPics > </span><span class="number">0</span><span> ) { </span></span></li><li class="alt"><span>   <span class="comment">// Now here you would do whatever you need to do with the images</span><span> </span></span></li><li><span>   <span class="comment">// For this example the images are just displayed</span><span> </span></span></li><li class="alt"><span>   <span class="keyword">for</span><span> ( $i=</span><span class="number">0</span><span>; $i < $iNumberOfPics ; $i++ ) { </span></span></li><li><span>     echo $aPics[<span class="number">0</span><span>][$i]; </span></span></li><li class="alt"><span>   }; </span></li><li><span>}; </span></li><li class="alt"><span> </span></li><li><span>endwhile; </span></li><li class="alt"><span>endif; </span></li><li><span>> </span></li></ol>

自动生成笑脸图案

被WordPress使用的另一个方法, 这段代码可使你把图像自动更换一个笑脸符号

<ol class="dp-j"><li class="alt"><span><span>$texte=</span><span class="string">'A text with a smiley '</span><span>; </span></span></li><li><span>echo str_replace(<span class="string">':-)'</span><span>,</span><span class="string">'<img  src="/static/imghwm/default1.png"  data-src="smileys/souriant.png"  class="lazy"   alt="15 Practical PHP Regular Expressions_PHP Tutorial" >'</span><span>,$texte); </span></span></li></ol>

移除图片的链接

<ol class="dp-j"><li class="alt"><span><span><meta http-equiv=</span><span class="string">"Content-Type"</span><span> content=</span><span class="string">"text/html; charset=utf-8"</span><span> /> </span></span></li><li><span><php </span></li><li class="alt"><span>  $str = ' </span></li><li><span>    <a href=<span class="string">"http://www.jobbole.com/"</span><span>>jobbole</a>其他字符 </span></span></li><li class="alt"><span>    <a href=<span class="string">"http://www.sohu.com/"</span><span>>sohu</a> </span></span></li><li><span>    <a href=<span class="string">"http://www.sohu.com/"</span><span>><img  src=</span alt="15 Practical PHP Regular Expressions_PHP Tutorial" ><span class="string">"http://www.fashion-press.net/img/news/3176/mot_06.jpg"</span><span> /></a> </span></span></li><li class="alt"><span>    <br>'; </span></li><li><span> </span></li><li class="alt"><span>  <span class="comment">//echo preg_replace("/(<a.*?>)(<img .*? alt="15 Practical PHP Regular Expressions_PHP Tutorial" >)(<\/a>)/", '$2', $str); </span><span> </span></span></li><li><span>  echo preg_replace(<span class="string">"/(<a.*?>)(<img .*? alt="15 Practical PHP Regular Expressions_PHP Tutorial" >)(<\/a>)/"</span><span>, </span><span class="string">'\2'</span><span>, $str);  </span></span></li><li class="alt"><span>> </span></li></ol>

以上就是15个超实用的php正则表达式,希望对大家的学习有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1078009.htmlTechArticle15 个实用的 PHP 正则表达式 对于开发人员来说,正则表达式是一个非常有用的功能,它提供了 查找,匹配,替换 句子,单词,或者其他格...
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
PyCharm新手指南:学会在PyCharm中删除项目PyCharm新手指南:学会在PyCharm中删除项目Feb 23, 2024 pm 09:39 PM

PyCharm新手指南:删除项目的实用技巧PyCharm是一款功能强大的Python集成开发环境(IDE),在进行项目开发时,有时候需要删除项目或项目中的文件。本文将介绍在PyCharm中删除项目的实用技巧,并提供具体的代码示例帮助新手更好地理解和应用。1.删除项目删除项目意味着删除整个项目文件夹,这在我们需要清理或重建项目时非常有用。在PyCharm中删

php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

全角英文字母转换为半角形式的实用技巧全角英文字母转换为半角形式的实用技巧Mar 26, 2024 am 09:54 AM

全角英文字母转换为半角形式的实用技巧在现代生活中,我们经常会接触到英文字母,在使用电脑、手机等设备时也经常需要输入英文字母。然而,有时候我们会遇到全角英文字母的情况,而我们需要使用的是半角形式。那么,如何将全角英文字母转换为半角形式呢?下面就为大家介绍一些实用的技巧。首先,全角英文字母和数字是指在输入法中占据一个全角位置的字符,而半角英文字母和数字则是占据一

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor