Rewrite PHP preg_replace in C #.
The PHP language has a very powerful function, mostly supported by its powerful functions. In this article, we will give you a detailed explanation of how PHP function Preg_replace () is used.
php function Preg_replace () Prototype: Mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
The PHP function Preg_replace () is more powerful than the C function. The first three parameters can be used arrays, the fourth parameter $limit can set the number of substitutions, the default is to replace all. Code 6.7 is an application instance of an array substitution.
php function Preg_replace () code 6.7 array substitution
Copy the code code as follows:
< PHP
String
$string = "Name: {name}< br>\nemail:
{email}< br>\naddress: {address}< br>\n ";
Mode
$patterns =array (
"/{address}/",
"/{name}/",
"/{email}/"
);
Replace string
$replacements = Array (
"No.5, Wilson St., New York, U.S.A",
"Thomas Ching",
"Tom@emailaddress.com",
);
Output mode substitution results
Print Preg_replace ($patterns,
$replacements, $string);
?>
The output results are as follows.
Name:thomas Ching ",
Email:tom@emailaddress.com
Address:no.5, Wilson St., New York, U.S.A
C#
Copy the code code as follows:
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;
}
The above is the implementation of PHP in C # preg_replace content, more related articles please pay attention to topic.alibabacloud.com (www.php.cn)!