user1720897
user1720897

Reputation: 1246

Unable to match subsequent regex pattern

I need to extract the following strings from the main string:

roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly,

roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly,

roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly

The main string is:

roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly, roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly, roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly

The regex I have is (roundcube.*?httponly){1} which matches the first string perfectly. However, it doesn't match the second or third occurrence, i.e (roundcube.*?httponly){2} and (roundcube.*?httponly){3}

Please let me know what am I doing wrong. I am trying to do this in PHP.

Upvotes: 1

Views: 144

Answers (2)

vks
vks

Reputation: 67968

(roundcube[\s\S]*?httponly)

You need to make . match newlines or use [\s\S] instead.Use i flag too.See demo.

https://regex101.com/r/fM9lY3/22

$re = "/(roundcube[\\s\\S]*?httponly)/mi"; 
$str = "roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly, roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly, roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly"; 

preg_match_all($re, $str, $matches);

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You explicitly tell the regex engine to match 1 occurrence only with a limiting quantifier {1}. Remove it and the regex will work.

Also, I suggest to make it safer with word boundaries:

\broundcube.*?\bhttponly\b

See demo (use ignorecase option!)

In PHP, just grab the matches, not groups.

$re = '/\broundcube.*?\bhttponly\b/i'; 
$str = "roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly, roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly, roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly"; 
preg_match_all($re, $str, $matches);
print_r($matches[0]);

In case you have newlines in your input, add the /s modifier so that . could also match newline symbols.

Upvotes: 2

Related Questions