title: Escaping string for use in regular expression
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1531456/is-there-a-php-function-that-can-escape-regex-patterns-before-they-are-applied">Is there a PHP function that can escape regex patterns before they are applied?</a>  </p>
  </blockquote>
  
  
  
  <p>I want to use a string stored in a variable in a regular expression. What's the best way (in PHP) to escape a string for use in a (PCRE) regular expression?</p>
  
  <p>For example,</p>
  
  <pre><code>$text = 'm/z';  // this is the text I want to use as part of my regular expression
  $text_regexp = '#' . $text . '#i';  // this is my regular expression
  </code></pre>
  
  <p>Would give</p>
  
  <pre><code>$text_regexp = '#m/z#i';
  </code></pre>
  
  <p>But I would want the following regular expression:</p>
  
  <pre><code>$text_regexp = '#m\/z#i';
  </code></pre>
  
  <p>This is a contrived example, but I wanted to illustrate the point simply.</p>