How to match characters

How to match special characters

Pattern Matches
\\ Backslash character
\/ Forward slash
\t Tab
\n New Line
\r Carriage Return
\f Form Feed
\xhh The Latin-1 character whose value is the two hexadecimal digits

Special characters

      $string = "© 2017 Mike's Music. \ All rights reserved (5/2017).";
      preg_match('/\xA9/', $string); // Matches © and returns 1
      preg_match('///', $string); // Returns FALSE and issues a warning
      preg_match('/\//', $string); // Matches / and returns 1
      preg_match('/\\\\/', $string); // Matches \ and returns 1
      

How to match types of characters

Pattern Matches
. Any single character except a new line character (use \. to match a period)
\w Any letter, number, or the underscore
\W Any character that’s not a letter, number, or the underscore
\d Any digit
\D Any character that’s not a digit
\s Any whitespace character (space, tab, new line, carriage return, form feed, or vertical tab)
\S Any character that’s not whitespace

Types of characters

      $string = 'The product code is MBT-3461.'; 
      preg_match('/MB./', $string); // Matches MBT and returns 1
      preg_match('/MB\d/', $string); // Matches nothing and returns 0
      preg_match('/MBT-\d/', $string); // Matches MBT-3 and returns 1
      

Description

Back