当前位置:首页 > PHP教程 > php函数 > 列表

php ereg_replace函数基础与实例代码

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-17 20:32:08 浏览: 评论:0 

语法:string ereg_replace(string $pattern,string $replacement,string $string)

修改后的字符串返回,如果没有找到匹配的字符串,那么将返回不变,实例代码如下:

  1. $string = "this phpfensi.com a test"; 
  2. echo str_replace(" phpfensi.com", " was", $string); 
  3. echo ereg_replace("( )phpfensi.com", "\1was", $string); 
  4. echo ereg_replace("(( )phpfensi.com)", "\2was", $string); 

有一点要注意的是,如果你使用一个整数参数值作为替代,您可能不会得到你期望的结果,这是因为ereg_replace()将解释为一个字符值序数,并套用,例如如下代码:

  1. $num = 4; 
  2. $string = "this string has four words."; 
  3. $string = ereg_replace('four', $num, $string); 
  4. echo $string;   /* output: 'this string has   words.' */ 
  5. /* this will work. */ 
  6. $num = '4'; 
  7. $string = "this string has four words."; 
  8. $string = ereg_replace('four', $num, $string); 
  9. echo $string;   /* output: 'this string has 4 words.' */ 

来看一个用ereg_replace获取连接代码,代码如下:

$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href="\0">\0</a>", $text);

取字符串中一部份,代码如下:

$output = ereg_replace("your regexp here", "<font color=red>\0</font>", $input) ;

print $output;

再来看一个更复杂的实例,代码如下:

  1. function strip_urls($text, $reppat) 
  2. { 
  3.     if(!$reppat){ 
  4.         $reppat = "text [url]"; 
  5.     } 
  6.     $aimpstr = 'php_strip_urls_function_by_real-php-geek'; 
  7.     //change $aimpstr to anything you want. 
  8.     $impstr = md5($aimpstr); 
  9.     $text = str_replace('</a>', '</a>' . $impstr, $text); 
  10.     $text = explode($impstr, $text); 
  11.     $n = 0; 
  12.     $texta = array(); 
  13.     $reppat = str_ireplace(array('text', 'url'), array('\4', '\2'), $reppat); 
  14.     foreach ($text as $text) { 
  15.         $texta[$n] = ereg_replace("<a(.*)href="(.*)"(.*)>(.*)</a>", $reppat, $text); 
  16.         $n++; 
  17.     } 
  18.     $textb = implode("</a>", $texta); 
  19.     return $textb; 
  20. } 

examples,代码如下:

  1. $string_of_text = '<a href="http://www.phpfensi.com/">php</a> rocks. <a href="http://www.phpfensi.com/">网页制作教程教程</a> also!'; 
  2. echo strip_urls($string_of_text, "text"); 
  3. echo strip_urls($string_of_text, "url"); 
  4. echo strip_urls($string_of_text, "text [url]"); 
  5. 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 或 $0 指的是被整个模式所匹配的文本,对左圆括号从左到右计数(从 1 开始)以取得子模式的数目.

对替换模式在一个逆向引用后面紧接着一个数字时(即:紧接在一个匹配的模式后面的数字),不能使用熟悉的 \1 符号来表示逆向引用,举例说 \11,将会使 preg_replace() 搞不清楚是想要一个 \1 的逆向引用后面跟着一个数字 1 还是一个 \11 的逆向引用。本例中的解决方法是使用 ${1}1,这会形成一个隔离的 $1 逆向引用,而使另一个 1 只是单纯的文字.

Tags: ereg_replace 函数基础

分享到:

相关文章