加入收藏 | 设为首页 | 会员中心 | 我要投稿 阜新站长网 (https://www.0418zz.cn/)- 基础存储、数据处理、视频终端、内容创作、网络安全!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php ereg_replace函数基础与实例代码

发布时间:2022-06-17 09:15:56 所属栏目:PHP教程 来源:互联网
导读:语法:string ereg_replace(string $pattern,string $replacement,string $string) 修改后的字符串返回,如果没有找到匹配的字符串,那么将返回不变,实例代码如下: $string = this phpfensi.com a test; echo str_replace( phpfensi.com, was, $string); echo e
  语法:string ereg_replace(string $pattern,string $replacement,string $string)
 
  修改后的字符串返回,如果没有找到匹配的字符串,那么将返回不变,实例代码如下:
 
  $string = "this phpfensi.com a test";
  echo str_replace(" phpfensi.com", " was", $string);
  echo ereg_replace("( )phpfensi.com", "1was", $string);
  echo ereg_replace("(( )phpfensi.com)", "2was", $string);
  有一点要注意的是,如果你使用一个整数参数值作为替代,您可能不会得到你期望的结果,这是因为ereg_replace()将解释为一个字符值序数,并套用,例如如下代码:
 
  $num = 4;
  $string = "this string has four words.";
  $string = ereg_replace('four', $num, $string);
  echo $string;   /* output: 'this string has   words.' */
  /* this will work. */
  $num = '4';
  $string = "this string has four words.";
  $string = ereg_replace('four', $num, $string);
  echo $string;   /* output: 'this string has 4 words.' */
  来看一个用ereg_replace获取连接代码,代码如下:
 
  $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=""></a>", $text);
 
  取字符串中一部份,代码如下:
 
  $output = ereg_replace("your regexp here", "<font color=red></font>", $input) ;
 
  print $output;
 
  再来看一个更复杂的实例,代码如下:
 
  function strip_urls($text, $reppat)
  {
      if(!$reppat){
          $reppat = "text [url]";
      }
      $aimpstr = 'php_strip_urls_function_by_real-php-geek';
      //change $aimpstr to anything you want.
      $impstr = md5($aimpstr);
      $text = str_replace('</a>', '</a>' . $impstr, $text);
      $text = explode($impstr, $text);
      $n = 0;
      $texta = array();
      $reppat = str_ireplace(array('text', 'url'), array('4', '2'), $reppat);
      foreach ($text as $text) {
          $texta[$n] = ereg_replace("<a(.*)href="(.*)"(.*)>(.*)</a>", $reppat, $text);
          $n++;
      }
      $textb = implode("</a>", $texta);
      return $textb;
  }
  examples,代码如下:
 
  $string_of_text = '<a href="http://www.phpfensi.com/">php</a> rocks. <a href="http://www.phpfensi.com/">网页制作教程教程</a> also!';
  echo strip_urls($string_of_text, "text");
  echo strip_urls($string_of_text, "url");
  echo strip_urls($string_of_text, "text [url]");
  echo strip_urls($string_of_text, null);
  说明:在 subject 中搜索 pattern 模式的匹配项并替换为 replacement,如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换.
 
  replacement 可以包含 n 形式或(自 php 4.0.4 起)$n 形式的逆向引用,首选使用后者。每个此种引用将被替换为与第 n 个被捕获的括号内的子模式所匹配的文本,n 可以从 0 到 99,其中 或 $0 指的是被整个模式所匹配的文本,对左圆括号从左到右计数(从 1 开始)以取得子模式的数目.
 
  对替换模式在一个逆向引用后面紧接着一个数字时(即:紧接在一个匹配的模式后面的数字),不能使用熟悉的 1 符号来表示逆向引用,举例说 11,将会使 preg_replace() 搞不清楚是想要一个 1 的逆向引用后面跟着一个数字 1 还是一个 11 的逆向引用。本例中的解决方法是使用 ${1}1,这会形成一个隔离的 $1 逆向引用,而使另一个 1 只是单纯的文字

(编辑:阜新站长网)

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

    推荐文章
      热点阅读