myol myol - 1 year ago 179
CSS Question

Escaping special characters in symfony css selector or using wildcard

I am using the

package to find a form with a name containing a number of css special chars

<input name="myfield[0].thing">

I am using

$messageElement = $crawler->filter('input[name=myField[0].thing]');

return $messageElement->attr($attribute);

But I get the error

Symfony\Component\CssSelector\Exception\SyntaxErrorException: Expected "]", but found.

Obviously this is because the symfony css selector is using
[ ]
to contain the attributes. So If I try an escape all the special chars


I now get empty output. How can I fix this?

Bonus question: is it possible to use a wildcard instead?
doesn't seem to work for me.

Answer Source

If you encapsulate the field name it should work, try this:

$messageElement = $crawler->filter('input[name="myField[0].thing"]');

return $messageElement->attr($attribute);.

For the bonus question, you can use a regex match similar to suggested here: wildcard * in CSS for classes

// For matching strings starting with a certain thing notice the ^=
$messageElement = $crawler->filter('input[name^="myField[0]"]');

// For matching strings containing with a certain thing notice the *=
$messageElement = $crawler->filter('input[name*="myField[0]"]');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download