skip to Main Content

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

2

Answers


  1. 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 )
    
    Login or Signup to reply.
  2. You have a non-greedy part in the pattern: .+?. It means it matches the minimum. So, you can modify the pattern to needs to match the comma or the end of the string ($): (,|$). If you chose this way your regex is:

    "/$siteId(.+?)(?:,|$)/"
    

    The ?: is just to skip this group to return it.

    See: https://regex101.com/r/LNKdgh/1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search