Search code examples
phpregexpreg-match

Regular Expression Help - PHP - preg_match()


Hope I don't get beaten up about this. I'm new to regex and I know there are tons of resources out there, but my problem is that I want to do a few specific things and I cant seem to figure out how to piece the expression together.

Say this is a snippet of my string:

AudienceTypes=Internal; InternallearnerName=Ryan Litwiller; uName=227812;

I want to search for InternallearnerName= and store what comes after = up to the semi colon as a variable.

As an alternative to preg_match() I have tried to start working out a solution using preg_split by semicolon, array_search(), then substr() but really thought a regex would be a much simpler solution.


Solution

  • Here you go:

    <?php
    $s='AudienceTypes=Internal; InternallearnerName=Ryan Litwiller; uName=227812;';
    preg_match( '/\bInternallearnerName=([^;]+)/', $s, $matches );
    echo $matches[1], "\n";
    

    The regular expression:

    • \b means 'word boundary', so it won't match FOOInternallearnerName=...
    • (..) defines a group; the first pair will be number 1.
    • [^..] is a single character that is NOT (^) one of the following; in this case ;. So, it matches any character except ;.
    • + means 1 or more.

    $matches will store the matches. $matches[0] will store the entire matched string, and $matches[1] the first group. ($matches[2] would store the second, except you only have one group (..) in the regular expression.

    To match the value of uName aswell use this:

    preg_match( '/\bInternallearnerName=([^;]+.*?\buName=([^;]+)/', $s, $matches );
    

    Here, $matches[2] will be 227812.

    Note that the first and last character of the regular expression, / in this case, are only there to mark the beginning/ending of the regular expression. Strictly speaking they are not needed, but this is probably legacy. You can use other characters there aswell; for instance, if you're matching URLs or file paths you could use @: preg_match( "@.....@", ....).

    Also, preg_match returns false if there is no match, so you should check for it: