Splitting Strings

You want to break a string apart based on something more complicated than a literal sequence of characters.

Use preg_split(). It splits up a string by some delimiter that marks the separation between the words in the string, such as a space or a colon or a combination of such characters. It returns an array of substrings.

<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
if (isset($_POST['submit'])) {
		process_form();
	}
	else {
		display_form();// display form for the first time
	}

function display_form() {
	echo <<<HTML
	<form action = "$_SERVER[SCRIPT_NAME]" method="post">
	Regular Expression Pattern (include the delimiter):<br />
	<input type="text" name="pattern" size="70" value="/[:,;]/m" /><br />
	<br />
	Text:<br />
	<textarea name="text" rows="5" cols="50">
	Fruits: apple, orange, banana;
	Vegetables: carrot, tomato, onion
	</textarea><br />
	<input type="submit" name="submit" value="Check" />
	</form>
	<table border>
	<tr bgcolor="lightcyan">
	<th align="left">Regular Expression</th>
	<th align="left">Text</th>
	</tr>
	<tr>
	<td>/[,;] ?/m</td>
	<td>apple;banana,cantaloupe;strawberry,watermelon
	</td>
	</tr>
	<tr bgcolor="lightyellow">
	<td></td>
	<td>
	</td>
	</tr>
	</table>
HTML;
}

function process_form() {
	// stripslashes and trim the strings
	$pattern = stripslashes(trim($_POST['pattern']));
	$text = trim($_POST['text']);
	echo "The result of splitting using <br /><font color=red>$pattern</font><br />
	against<br /><font color=red>$text</font><br /> is:<br />";
	// match the pattern
	$matches = preg_split($pattern, $text);
	echo "<br />The matches array contains:<br />";
	foreach ($matches as $key =>$values) {
		echo $key, " => ", $values, "<br />";
	}
	echo "<br /><a href=\"$_SERVER[SCRIPT_NAME]\">Check again?</a>";

}
?>
</p>
</body>
</html>

View the effect


Regular Expressions | Introduction | Matching a Pattern | Metacharacters | Quantifiers | Character Classes | Pattern Modifiers | Matching and Replacing Patterns | Splitting Strings | Finding Elements of an Array | Finding the nth Occurence of a Match | Choosing Greedy or Nongreedy matches
© 2008: Hann So
email: hso@voyager.deanza.edu