Preg_replace in PHP is implemented in c-sharp

  • 2020-03-31 20:04:21
  • OfStack

PHP preg_replace was rewritten with c#.
The PHP language is very powerful, mainly because of its powerful functions to support. In this article, we'll explain how to use the PHP function preg_replace() in more detail.
Preg_replace () preg_replace(mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
The PHP function preg_replace() is more powerful than c. The first three parameters can be used array; The fourth parameter, $limit, allows you to set the number of substitutions, and by default, all substitutions. Code 6.7 is an example of an array substitution application.
PHP function preg_replace() code 6.7 array replacement
 
< ?php 
//string
$string = "Name: {Name}< br>nEmail: 
{Email}< br>nAddress: {Address}< br>n"; 
//model
$patterns =array( 
"/{Address}/", 
"/{Name}/", 
"/{Email}/" 
); 
//Replacement string
$replacements = array ( 
"No.5, Wilson St., New York, U.S.A", 
"Thomas Ching", 
"tom@emailaddress.com", 
); 
//Output mode replacement results
print preg_replace($patterns, 
$replacements, $string); 
?> 

The output is as follows.
Name: Thomas Ching ",
Email: tomaddress.com
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; 
} 

Related articles: