Thursday, December 31, 2009

C# Equivalent of PHP preg_split

PHP's preg_split allows for you to split a string into an array by using a regular expression. For example, the following code will split the string my_string by one or more whitespace characters.


$my_string = "test 1 2 3";
$word_list = preg_split("/[\s]+/",trim($my_string));



The equivalent code in C# would look like this.


using System.Text.RegularExpressions;

string my_string = "test 1 2 3";
string[] word_list= Regex.Split(my_string, @"\s+");



Both should produce an array with 4 elements: test, 1, 2, and 3.

MSDN Link