RegEx with preg_match to find and replace a SIMILAR string <p>I am using regular expressions with <code>preg_replace()</code> in order to find and replace a sentence in a piece of text. The <code>$search_string</code> contains plain text + html tags + <code>&amp;nbsp;</code> elements. The problem is that only sometimes the <code>&amp;nbsp;</code> elements convert to white space on run time, making it difficult to find and replace using <code>str_replace()</code>. So, I'm trying to build a pattern that is equal to the search string and will match anything like it which contains, or does not contain the <code>&amp;nbsp;</code> elements;</p> <p>For example:</p> <pre><code>$search_string = 'Two years in,&amp;nbsp;the company has expanded to 35 cities, five of which are outside the U.S. Plus,&amp;nbsp;in&amp;nbsp;April, &lt;a href="site.com"&gt;ClassPass&lt;/a&gt; acquired its main competitor,&amp;nbsp;Fitmob.'; </code></pre> <p><code>$pattern</code> = <code>$search_string</code>(BUT IGNORE THE <code>&amp;nbsp;</code> elements in the subject)</p> <pre><code>$subject = "text text text text text". $search_string . "text text text text text"; </code></pre> <p>Using <a href="http://stackoverflow.com/questions/2078915/a-regular-expression-to-exclude-a-word-string">A regular expression to exclude a word/string</a>, I've tried:</p> <pre><code> $pattern = '`^/(?!\&amp;nbsp;)'.$search_string.'`'; $output = preg_replace($pattern, $replacement_string,$subject); </code></pre> <p>The end result will be that if the $subject does contains a string that is like my <code>$seach_string</code> but without the <code>&amp;nbsp;</code> elements, it will still match and replace it with <code>$replacement_string</code></p> <p><strong>EDIT:</strong></p> <p>The actual values:</p> <pre><code>$subject = file_get_contents("http://venturebeat.com/2015/11/10/sources-classpass-raises-30-million-from-google-ventures-and-others/"); $search_string = "Two years in,&amp;nbsp;the company has expanded to 35 cities, five of which are outside the U.S. Plus,&amp;nbsp;in&amp;nbsp;April, ClassPass acquired its main competitor,&amp;nbsp;Fitmob."; $replacement_string = "&lt;span class='smth'&gt;Two years in,&amp;nbsp;the company has expanded to 35 cities, five of which are outside the U.S. Plus,&amp;nbsp;in&amp;nbsp;April, ClassPass acquired its main competitor,&amp;nbsp;Fitmob.&lt;/span&gt;"; </code></pre>