把php preg_replace 用c# 重写了一下。 PHP语言的功能非常强大,主要就是靠它强大的函数来作支撑。我们在这篇文章中将会为大家详细讲解有关PHP函数preg_replace()的相关使用方法。 PHP函数preg_replace()原型:mixed preg_replace (mixed $pattern,mixed $replacement,mixed $subject [,int $limit]) PHP函数preg_replace()较c的功能更加强大。其前三个参数均可以使用数组;第四个参数$limit可以设置替换的次数,默认为全部替换。代码6.7是一个数组替换的应用实例。 PHP函数preg_replace()代码6.7 数组替换 <div class="codetitle"><a style="CURSOR: pointer" data="60847" class="copybut" id="copybut60847" onclick="doCopy('code60847')"> 代码如下:<div class="codebody" id="code60847"> < ?php //字符串 $string = "Name: {Name}< br>nEmail: {Email}< br>nAddress: {Address}< br>n"; //模式 $patterns =array( "/{Address}/", "/{Name}/", "/{Email}/" ); //替换字串 $replacements = array ( "No.5,Wilson St.,New York,U.S.A", "Thomas Ching", "tom@emailaddress.com", ); //输出模式替换结果 print preg_replace($patterns, $replacements,$string); ?> 输出结果如下。 Name: Thomas Ching", Email: tom@emailaddress.com Address: No.5,U.S.A c# <div class="codetitle"><a style="CURSOR: pointer" data="52561" class="copybut" id="copybut52561" onclick="doCopy('code52561')"> 代码如下:<div class="codebody" id="code52561"> public static String PregReplace(this String input,string[] pattern,string[] replacements) { if (replacements.Length != pattern.Length) throw new ArgumentException("Replacement and Pattern Arrays must be balanced"); for (var i = 0; i < pattern.Length; i++) { input = Regex.Replace(input,pattern[i],replacements[i]); } return input; }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|