php ereg_replace函数基础与实例代码
语法:string ereg_replace(string $pattern,string $replacement,string $string)
修改后的字符串返回,如果没有找到匹配的字符串,那么将返回不变,实例代码如下:
$string = "this phpfensi测试数据 a test" ; echo str_replace ( " phpfensi测试数据" , " was" , $string ); echo ereg_replace ( "( )phpfensi测试数据" , "\1was" , $string ); echo ereg_replace ( "(( )phpfensi测试数据)" , "\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="\0">\0</a>", $text);
取字符串中一部份,代码如下:
$output = ereg_replace("your regexp here", "<font color=red>\0</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://HdhCmsTestphpfensi测试数据/">php</a> rocks. <a href="http://HdhCmsTestphpfensi测试数据/">网页制作教程教程</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 或 $0 指的是被整个模式所匹配的文本,对左圆括号从左到右计数(从 1 开始)以取得子模式的数目.
对替换模式在一个逆向引用后面紧接着一个数字时(即:紧接在一个匹配的模式后面的数字),不能使用熟悉的 \1 符号来表示逆向引用,举例说 \11,将会使 preg_replace() 搞不清楚是想要一个 \1 的逆向引用后面跟着一个数字 1 还是一个 \11 的逆向引用。本例中的解决方法是使用 ${1}1,这会形成一个隔离的 $1 逆向引用,而使另一个 1 只是单纯的文字.
查看更多关于php ereg_replace函数基础与实例代码 - php函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did30845