加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php 正则 ereg_replace替换

发布时间:2020-12-13 20:28:52 所属栏目:PHP教程 来源:网络整理
导读:ereg_replace -- 正则表达式替换(php 3,php 4,php 5) string ereg_replace(string pattern,string replacement,string string) 本函数在 string 中扫描与 pattern 匹配的部分,并将其替换为 replacement,返回替换后的字符串,(如果没有可供替换的匹配项则会返

ereg_replace -- 正则表达式替换(php 3,php 4,php 5)

string ereg_replace(string pattern,string replacement,string string)

本函数在 string 中扫描与 pattern 匹配的部分,并将其替换为 replacement,返回替换后的字符串,(如果没有可供替换的匹配项则会返回原字符串):

  1. <?php 
  2. $string = "this is a test"
  3. echo str_replace(" is"" was"$string); 
  4. echo ereg_replace("( )is""1was"$string); 
  5. echo ereg_replace("(( )is)""2was"$string); 
  6. ?> 
  7. //输出如下: 
  8. //that was a test 
  9. //that was a test 
  10. //that was a test 

<td class='title'>热卖oou限量版双人浴巾</td>

整个替换为空,还是将

<td class='title'>热卖oou限量版双人浴巾</td>

替换成

<td class='title'></td>

第一种:echo preg_replace('/(<td[^<>]+title[^<>]+>)[^<>]*(</td>)/i','',$html);

第二种:echo preg_replace('/(<td[^<>]+title[^<>]+>)[^<>]*(</td>)/i','$1$2',$html);

首先这个正则表达式匹配 类似格式:

<td*title*>*</td>,这里每个星号*代表的是多个任意字符,相当于每个*对应正则里的[^<>]+,为了匹配准确,这里任意字符里不包含'<','>'.

对于第二种里的替换字符串$1和$2,分别为正则表达式里对应的两组()内匹配的值.这种形式正则里叫 子模式匹配.$1和$2叫反向匹配的结果.

这里$1匹配的结果是<td class='title'>,$2匹配的结果是</td>.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读