0

I have a variable called $value that contains a string with a css expression. It can be a value or a function: rgb( 25, 128, 128 );, transform( -50% -50% );, bottom 50px right 100px;, #198080;, bold;, 1px solid red;

I want to be able to identify if the expression contains a function or a string

$real_value = (is_numeric($value)) ?
    $value :
    (is_string($value) ?
        (preg_match('/^\w/', $value) ? $value : '"' . $value . '"') :
        '"'. $value . '"');

The idea is to assign to $real_value the value inside quotation marks like this: "#198080"; or this "bottom 50px right 100px"; but if it is a function, just return the same expression.

I started creating my regular expression, but I can't go past the first parentheses without breaking it: /^\w\-?\w?\(/

So I need to create a regular expression that checks if the string has the structure of a css function. There are not many of them (https://www.w3schools.com/cssref/css_functions.php) or just write one that checks for the parentheses

4
  • 5
    You might want to use some kind of a CSS parser rather than a regex. Commented Oct 21, 2024 at 16:40
  • 1
    To check for a structure of those css functions \b(?:attr|calc|conic-gradient|counter|cubic-bezier|hsla?|max|min|(?:(?:linear|radial)|repeating-(?:conic|linear|radial))-gradient|rgba?|var)\([^()]*\);? and then extend the list if needed regex101.com/r/OER19M/1 Commented Oct 22, 2024 at 9:42
  • 1
    @the are you supplying resolving advice as a comment? Commented Oct 22, 2024 at 10:04
  • “or just write one that checks for the parentheses” - this one seems the simpler and more future proof, and you can just use str_contains. There’s definitely exceptions, for instance with the content property, but those would then start with a quote of some sort. Commented Oct 22, 2024 at 11:46

0

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.