Question

I am trying to get this regex to match (once or twice) any occurrence of these strings: border-box|padding-box|content-box

Here is the regex:

((?:border-box|padding-box|content-box){1,2})

Here is the sample string:

background: url("my image.jpg") left right 2px 50% 75% repeat-x round scroll border-box padding-box;

Expected result:

border-box padding-box

Actual result:

Array
(
    [0] => border-box
    [1] => border-box
)

Oh and btw I am using this site to test my regex: http://www.phpliveregex.com/ Note: I am using preg_match not preg_match_all

Was it helpful?

Solution 2

The problem is that your pattern requires the repetitions to occur immediately after each other, with no whitespace between.

Try adding a \s* after the alternation to allow for optional whitespace between the repetitions, like this:

(?:(?:border-box|padding-box|content-box)\s*){1,2}

Or even better:

(?:(?:border|padding|content)-box\s*){1,2}

Note that because of the *, this will also match a string like border-boxborder-box (no whitespace between repetitions). If this is a problem you can try a pattern like this:

(?:(?:border|padding|content)-box)(?:\s+(?:border|padding|content)-box)?

Note that I've removed the surrounding (…) since this group would always be identical to the entire match, so it's almost certainly not necessary.

OTHER TIPS

Solution using preg_match_all()

You're trying to match multiple values, so use preg_match_all() instead of preg_match():

$ok = preg_match_all('/(border-box|padding-box|content-box)/', $str, $matches);

if ($ok) {
    $result = implode(' ', $matches[0]);
    var_dump($result);
}

Output:

string(22) "border-box padding-box"

Demo

Solution using preg_match()

Your current regular expression doesn't work because it doesn't take whitespace into account. You can modify the regular expression as follows.

((?:(?:border-box|padding-box|content-box)\s*){1,2})

Explanation:

  • (?:border-box|padding-box|content-box) - non-capturing group
  • \s* - match any whitespace character (shorthand for the character class[\r\n\t\f ]) zero or more times
  • {1,2} - match the previous group between 1 and 2 times

Output:

string(22) "border-box padding-box"

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top