RegEx Matching, Replacing, Splitting

Matching using the preg_match() function. Requires the pattern to be enclosed with delimiters, usually /, followed by the target string and an optional 3rd parameter for storing found matches.

 

preg_match("/pattern/", target, match) ;

 

<?php
	$target = "If you can't explain it simply, you don't understand it well enough." ;

	$pattern = "simply" ;

	if (preg_match("/$pattern/", $target, $match)) { //returns 1 for a match

		echo "Found: $match[0]";

	} else {

		echo "Couldn't find: $pattern";
	}
?>

Displays:

Found: simply

 

 

Replacing using the preg_replace() ; function. Requires the pattern to be enclosed with delimiters, usually /, followed by the replacement string, then the target string and an optional 4th parameter specifying how many replacements

 

preg_replace("/pattern/", replace, target, limit) ;

<?php
	$target = "If you can't explain it simply, you don't understand it well enough." ;

	$pattern = "simply" ;

	$replace = "in plain English" ;

	echo preg_replace("/$pattern/", $replace, $target);
?>

Displays:

If you can't explain it in plain English, you don't understand it well enough.

 

 

Splitting using the preg_split() ; function. Requires the pattern to be enclosed with delimiters (usually / ), followed by the replacement string, then the target string and an optional 4th parameter specifying how many replacements.

 

Returns an array of items that did NOT match the regex pattern.

 

preg_split("/pattern/", replace, target, limit) ;

 

This example uses a regex to split the string by any number of commas or space characters:

 

<?php
	$source = "If you can't explain it simply, you don't understand it well enough." ;

	$pattern = "[\s,]+" ;

	$words = preg_split("/$pattern/", $source);

	echo "<pre>";

	print_r( $words );

	echo "</pre>";
?>

Displays:

Array
(
[0] => If
[1] => you
[2] => can't
[3] => explain
[4] => it
[5] => simply
[6] => you
[7] => don't
[8] => understand
[9] => it
[10] => well
[11] => enough.
)

 

 

Similar to the above, the preg_grep() function returns an array of items, but this time those that matched the regex pattern:

 

<?php
	$bikes = array("Ducati", "Yamaha", "Honda", "Suzuki", "Kawasaki") ;

	$matches = preg_grep('/^[m-z]/i', $bikes);

	echo "<pre>";

	print_r( $matches );

	echo "</pre>";
?>

Displays:

Array
(
[1] => Yamaha
[3] => Suzuki
)

 

Leave a Reply