Regular Expressions Part 4 – Array Processing

PHP’s preg_split() function enables you to break a string apart basing on something more complicated than a literal sequence of characters. When it’s necessary to split a string with a dynamic expression rather than a fixed one, this function comes to the rescue. The basic idea is the same as preg_match_all() except that, instead of returning matched pieces of the subject string, it returns an array of pieces that didn’t match the specified pattern. The following example uses a regular expression to split the string by any number of commas or space characters:

<?php
‘——————————————————
$keywords = preg_split(“/[\s,]+/”, “php, regular expressions”);
print_r( $keywords );
‘——————————————————
?>

Another useful PHP function is the preg_grep() function which returns those elements of an array that match a given pattern. This function traverses the input array, testing all elements against the supplied pattern. If a match is found, the matching element is returned as part of the array containing all matches. The following example searches through an array and all the names starting with letters A-J:

<?php
‘——————————————————
$names = array(‘Andrew’,’John’,’Peter’,’Nastin’,’Bill’);
$output = preg_grep(‘/^[a-m]/i’, $names);
print_r( $output );
‘——————————————————
?>

Posted in Blogs, General PHP

Leave a Reply