Search code examples
phpregexpreg-match

PHP - Issue matching in string with preg_match


I have a string that contains a list of comma separated values.

eg: $sitelist = 'SC001rug,SC002nw,SC003nrge';

I'm using preg_match to check if a site is in this string and then return the characters after the ID.

$siteId='SC001';

if ( preg_match( "/$siteId(.+?),/", $sitelist, $matches ) ) {
    var_dump( $matches );
} else {
    echo "no match";
}

Using this it returns the results correctly:

array(2) { [0]=> string(9) "SC001rug," [1]=> string(3) "rug" }

However if $sitelist doesn't contain the trailing comma the match doesn't happen correctly.

$sitelist = 'SC001rug'; Results in 'no match'

If I remove the comma from the preg_match command it only returns the first character.

if ( preg_match( "/$siteId(.+?)/", $sitelist, $matches ) ) {

results in :

array(2) { [0]=> string(6) "SC001r" [1]=> string(1) "r" }

How do I right the preg_match so it will match with and without the trailing comma.

Thanks


Solution

  • Assuming the characters after the ID are always lower case or upper case letters, you can use this:

    preg_match( "/$siteId([a-zA-Z]+)/", $sitelist, $matches )