Home >Backend Development >C#.Net Tutorial >Implementation of preg_replace in php in c#
Rewrote php preg_replace in c#.
The PHP language is very powerful, mainly supported by its powerful functions. In this article, we will explain in detail how to use the PHP function preg_replace().
PHP function preg_replace() prototype: mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
PHP function preg_replace() is more powerful than c. The first three parameters can all use arrays; the fourth parameter $limit can set the number of replacements, and the default is to replace all. Code 6.7 is an application example of array replacement.
PHP function preg_replace() code 6.7 Array replacement
Copy the code as follows:
< ?php
//String
$string = "Name: {Name}< br>nEmail:
{Email}< br> ;nAddress: {Address}< br>n";
//Pattern
$patterns =array(
"/{Address}/",
"/{Name}/",
"/{Email}/"
);
//Replacement string
$replacements = array (
"No.5, Wilson St., New York, U.S.A",
"Thomas Ching",
"tom@emailaddress.com",
);
/ /Output pattern replacement 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 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 content of implementing preg_replace in php in c#, more related Please follow the PHP Chinese website (www.php.cn) for articles