Why does preg_quote escape < and > ?

  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

The following code

PHP Code: [ Select ]
<?php
 
$str = '. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -';
echo preg_quote($str);
 
?>
 
  1. <?php
  2.  
  3. $str = '. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -';
  4. echo preg_quote($str);
  5.  
  6. ?>
  7.  


Produces the following output

Code: [ Select ]
\. \\ \+ \* \? \[ \^ \] \$ \( \) \{ \} \= \! \< \> \| \: -


But why is it escaping the < and > ?

I don't get any errors and it matches as expected if I do this

PHP Code: [ Select ]
<?php
$str = '. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -';
echo preg_match('#<#', $str) ? 'yes' : 'no';
?>
  1. <?php
  2. $str = '. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -';
  3. echo preg_match('#<#', $str) ? 'yes' : 'no';
  4. ?>


< and > aren't even listed as special characters in the manual that I can find. :scratchhead:
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

The left angle bracket is used in lookbehind assertions:

http://www.php.net/manual/en/regexp.ref ... rtions.php

And the right angle bracket is used in some subpattern matching:

http://www.php.net/manual/en/regexp.ref ... lyonce.php
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

Seems like the escape is only needed if the bracket will be part of a pattern that could end up being interpreted as one of those multi-character meta-characters.

Kinda like the hyphen in a range [] will be matched as a literal hyphen at the end of the range and be interpreted as a range between A and Z if used between them.

Spooky I tell you.

Post Information

  • Total Posts in this topic: 3 posts
  • Users browsing this forum: No registered users and 66 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.