myol myol - 1 month ago 25
CSS Question

Escaping special characters in symfony css selector or using wildcard

I am using the

Symfony\Component\DomCrawler\Crawler
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

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


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

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]"]');