title: PHP preg_replace markdown issue - detecting duplicates
body: <p>In a project I am building I would like to use markdown as follows</p>
  
  <pre><code>*text* = &lt;em&gt;text&lt;/em&gt;
  **text** = &lt;strong&gt;text&lt;/strong&gt;
  ***text*** = &lt;strong&gt;&lt;em&gt;text&lt;/em&gt;&lt;strong&gt;
  </code></pre>
  
  <p>As those are the only three markdown formats I require, I would like to remain lightweight and avoid importing the entire PHP markdown library as that would introduce features I do not require and create issues.</p>
  
  <p>So I have been trying to build some simple regex replaces. Using preg_replace I run:</p>
  
  <pre><code>'/(\*\*\*)(.*?)\1/' to '&lt;strong&gt;&lt;em&gt;\2&lt;/em&gt;&lt;/strong&gt;'
  
  '/(\*\*)(.*?)\1/' to '&lt;strong&gt;\2&lt;/strong&gt;'                                                                      
  
  '/(\*)(.*?)\1/' to '&lt;em&gt;\2&lt;/em&gt;',      
  </code></pre>
  
  <p>And this works great! em, bold, and the combo all work fine...</p>
  
  <p>But if the user makes a mistake or enters to many stars, everything breaks.</p>
  
  <p>i.e.</p>
  
  <pre><code>****hello**** = &lt;strong&gt;&lt;em&gt;&lt;em&gt;hello&lt;/em&gt;&lt;/strong&gt;&lt;/em&gt;
  *****hello***** = &lt;strong&gt;&lt;em&gt;&lt;strong&gt;hello&lt;/em&gt;&lt;/strong&gt;&lt;/strong&gt;
  ******hello****** = &lt;strong&gt;&lt;em&gt;&lt;/em&gt;&lt;/strong&gt;hello&lt;strong&gt;&lt;em&gt;&lt;/em&gt;&lt;/strong&gt;
  etc
  </code></pre>
  
  <p>When ideally it would create</p>
  
  <pre><code>****hello**** = *&lt;strong&gt;&lt;em&gt;hello&lt;/em&gt;&lt;/strong&gt;*
  *****hello***** = **&lt;strong&gt;&lt;em&gt;hello&lt;/em&gt;&lt;/strong&gt;**
  ******hello****** = ***&lt;strong&gt;&lt;em&gt;hello&lt;/em&gt;&lt;/strong&gt;***
  etc
  </code></pre>
  
  <p>Ignoring the un-required stars (so it would become clear to the user they made a mistake, and more importantly, the rendered HTML remains valid).</p>
  
  <p>I presume there must be some way to modify my regex to do this but I cannot for the life of my work it out, even after a whole day trying!</p>
  
  <p>I would also be happy with the result of </p>
  
  <pre><code>******hello****** = &lt;strong&gt;&lt;em&gt;hello&lt;/em&gt;&lt;/strong&gt;
  </code></pre>
  
  <p>So please, can anybody help me?</p>
  
  <p>Also please consider uneven stars. In this case the below scenario would be ideal.</p>
  
  <pre><code>***hello* = **&lt;em&gt;hello&lt;/em&gt;
  </code></pre>
  
  <p>And the time when a star should be part of the body and not detected, such as if a user inputs:</p>
  
  <pre><code>'terms and conditions may apply*'
  
  or
  
  'I give the film 5* out of 10'
  </code></pre>
  
  <p>Many many thanks</p>