preg_match – regular expression

Here is a good link for a cheat sheet for regular expressions that if you forget some of the syntax.

Here are some quick notes about regular expression in PHP that allow you to pull out information from a string of text.

$stringofvalues = "hi there from me - and now after that lets!!";
preg_match("/^.* - (.*)!!/", $stringofvalues, $matches);
print_r($matches);

and the output would be

Array
(
    [0] => hi there from me - and now after that lets!!
    [1] => and now after that lets
)

where the first array [0] is always the string that was passed in, and any matches that you picked are in the following index’s in the array (because the first match [0] in the array is the real string because it has matched that already 🙂 ) and then the second matches that you want to check for are within the regular expression ( .. ) brackets, so in my regular expression

/^.* - (.*)!!/

this means start at the beginning of the string ‘^’ and then any character ‘.’ 0 or more times ‘*’ find un-till you find a string as ” – ” (which is within the string to be searched) and then now copy any character 0 or more times ‘.*’ but this time place it into a matched index within the array by using the () around that regular expression search.

So if you wanted to pull back 2 matches from that string, then you could do something like

preg_match("/^(.*) - (.*)!!/", $stringofvalues, $matches);
print_r($matches);

Which the output would be

Array
(
    [0] => hi there from me - and now after that lets!!
    [1] => hi there from me
    [2] => and now after that lets
)

where the first part of the string (before the ” – “) is within the 1st index of the matches array and then the second search match is within the 2nd index of the matches array.

Leave a Reply

Your email address will not be published. Required fields are marked *