Search code examples
phpregexbehat

PhP function to validate Xpath or CSS - Behat


I have the function findElements on Behat that has a validation to check if what I have passed as a parameter is a Xpath or a CSS Selector. This is the validation part:

// If it starts with //, it's a xpath
if (preg_match("/^\/\/.*|^\(.*\)\[(\d+|last\(\))\]$/", $selector) === 1) {
            $type = 'xpath';
        } else {
            $type = 'css';
        }

The thing is: sometimes, I need to use Xpath like this one:

(//div[@class='views-element-container form-group'])[1]/div/div/h3

It does not starts with //, so the validation thinks this is a CSS selector, and not a Xpath.

What I need: Include in the validation that the Xpath can also starts with (//.

Thanks!


Solution

  • Just add a possible ( to the beginning of your regex by adding \(? after the caret like this:

    preg_match("/^\(?\/\/.*|^\(.*\)\[(\d+|last\(\))\]$/", $selector)