fork download
  1. <?php
  2. $balanced_string_regex = "~(?x) # Free-Spacing
  3. (?(DEFINE) # Define a few subroutines
  4. (?<double>&ldquo;(?:(?!&[lr]squo;).)*&rdquo;) # full set of doubles (no quotes inside)
  5. (?<single>&lsquo;(?:(?!&[lr]dquo;).)*&rsquo;) # full set of singles (no quotes inside)
  6. (?<notquotes>(?:(?!&[lr][sd]quo;).)*) # chars that are not quotes
  7. ) # end DEFINE
  8.  
  9. ^ # Start of string
  10. (?: # Start non-capture group
  11. (?&notquotes) # Any non-quote chars
  12. &l(?<type>[sd])quo; # Opening quote, capture single or double type
  13. # any full singles, doubles, not quotes or recursion
  14. (?:(?&single)|(?&double)|(?&notquotes)|(?R))*
  15. &r\k<type>quo; # Closing quote of the correct type
  16. (?&notquotes) #
  17. )++ # Repeat non-capture group
  18. $ # End of string
  19. ~";
  20.  
  21. $string = "&ldquo;He said &rdquo; &lsquo;He said &rsquo;";
  22. check_string($string);
  23. $string = "<p>&ldquo;Wait a moment,&rdquo; Jacey said. The street light lit up his aged, rat face. Who&rsquo;s on the move?&rdquo;</p>";
  24. check_string($string);
  25. $string = "<p>&ldquo;Wait a moment,&rdquo; Jacey said. The street light lit up his aged, rat face. &lsquo;Whos on the &ldquo;move?&rdquo; &rsquo;</p>";
  26. check_string($string);
  27. $string = "<p>&ldquo;He said he&rsquo; coming afer you,&rdquo; Harry said, and he&rsquo; bringing the boys too!&rdquo;</p>";
  28. check_string($string);
  29. $string = "<p>&ldquo;He &lsquo;said he&rsquo; coming afer you,&rdquo; Harry said, and he&ldquo; bringing the boys too!&rdquo;</p>";
  30. check_string($string);
  31.  
  32.  
  33. function check_string($string) {
  34. global $balanced_string_regex;
  35. echo (preg_match($balanced_string_regex, $string)) ?
  36. "Balanced!\n" :
  37. " Nah... Not Balanced.\n" ;
  38. }
  39.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Balanced!
 Nah... Not Balanced.
Balanced!
 Nah... Not Balanced.
Balanced!