Escaper.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. /*
  3. * This file is part of the Mink package.
  4. * (c) Konstantin Kudryashov <ever.zet@gmail.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. namespace Behat\Mink\Selector\Xpath;
  10. /**
  11. * XPath escaper.
  12. *
  13. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  14. */
  15. class Escaper
  16. {
  17. /**
  18. * Escapes the string as a XPath literal.
  19. *
  20. * @param string $s
  21. *
  22. * @return string
  23. */
  24. public function escapeLiteral($s)
  25. {
  26. if (false === strpos($s, "'")) {
  27. return sprintf("'%s'", $s);
  28. }
  29. if (false === strpos($s, '"')) {
  30. return sprintf('"%s"', $s);
  31. }
  32. $string = $s;
  33. $parts = array();
  34. while (true) {
  35. if (false !== $pos = strpos($string, "'")) {
  36. $parts[] = sprintf("'%s'", substr($string, 0, $pos));
  37. $parts[] = "\"'\"";
  38. $string = substr($string, $pos + 1);
  39. } else {
  40. $parts[] = "'$string'";
  41. break;
  42. }
  43. }
  44. return sprintf('concat(%s)', implode($parts, ','));
  45. }
  46. }