当前位置: 首页 > 图文教程 > 网络编程 > PHP > c#中的实现php中的preg_replace

PHP
Studio Client 安装指导
Discuz!用户怎样减少广告灌水机的骚扰
X-Space(1):日志发布后首页为何不更新
X-Space(2):X-Space"搬家"三步走
X-Space(3):如何屏蔽敏感字符
X-Space(4):如何在个人博客设置音乐播放
rss的语言编码大全
rss 使用规范
htaccess文件使用大全
什么是 unicode
php5 新增加的参数设置
探索字串的奥秘
apache中.htaccess文件的功能写法
半小时精通正则表达式
统一建模语言UML轻松入门之类和对象
十天学习PHP之第二天
十天学习PHP之第三天
十天学习PHP之第四天
最完整的editplus之php语法文件
cookie与session

PHP 中的 c#中的实现php中的preg_replace


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 58 ::
收藏到网摘: n/a

最近在按照一个php项目用c#重写,一边学习同时发现了他们的神似神不似的很多地方 把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 数组替换
复制代码 代码如下:

< ?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",
"[email protected]",
);
//输出模式替换结果
print preg_replace($patterns,
$replacements, $string);
?>

输出结果如下。
Name: Thomas Ching",
Email: [email protected]
Address: No.5, Wilson St., New York, U.S.A
c#
复制代码 代码如下:

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;
}