2

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

2 Answers 2

2

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 )
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I will try this. The characters are always lower case.
Then you can simply use regex like this: "/$siteId([a-z]+)/"
Thanks. This seems to work, is there any benefit over the suggestion by @hNczy ?
I don’t know your specific use case but as you stated, you want to omit the comma in regex, solution by @hNczy doesn’t omit the comma so in my opinion, his solution isn’t correct, even though it works.
0

You could make use of \K and match 1 or more non whitespace characters excluding a comma instead of using a capture group. If you don't want to cross a newline, you could use [^\n,]+ instead of [^\s,]+

SC001\K[^\s,]+

Regex demo | PHP demo

If you only want to match lowercase characters:

SC001\K[a-z]+

For your current $siteId that you are going to use as part of your regex you don't need it, but note that you can make use of preg_quote that "puts a backslash in front of every character that is part of the regular expression syntax".

$sitelist = 'SC001rug,SC002nw,SC003nrge';
$siteId = preg_quote('SC001', '/');
$regex = "/$siteId\K[^\s,]+/";

if (preg_match($regex, $sitelist, $matches)) {
    var_export($matches);
} else {
    echo "no match";
}

Output

array (
  0 => 'rug',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.