Identifying a random repeating pattern in a structured text string
<p>I have a string that has the following structure:</p>

<p><code>ABC_ABC_PQR_XYZ</code></p>

<p>Where PQR has the structure:</p>

<p><code>ABC+JKL</code></p>

<p>and</p>

<p><code>ABC</code> itself is a string that can contain alphanumeric characters and a few other characters like "_", "-", "+", "." and follows no set structure:</p>

<p>eg.<code>qWe_rtY-asdf</code> or <code>pkl123</code></p>

<p>so, in effect, the string can look like this:</p>

<p><code>qWe_rtY-asdf_qWe_rtY-asdf_qWe_rtY-asdf+JKL_XYZ</code></p>

<p>My goal is to find out what string constitutes <code>ABC</code>.</p>

<p>I was initially just using </p>

<pre><code>$arrString = explode("_",$string);
</code></pre>

<p>to return <code>$arrString[0]</code> before I was made aware that <code>ABC</code> (<code>$arrString[0]</code>) itself can contain underscores, thus rendering it incorrect.</p>

<p>My next attempt was exlpoding it on "_" anyway and then comparing each of the exploded string parts with the first string part until I get a semblance of a pattern:</p>

<pre><code>function getPatternABC($string)
{
 $count  = 0;
 $pattern ="";

 $arrString = explode("_", $string);

 foreach($arrString as $expString)
 {
    if(strcmp($expString,$arrString[0])!==0 || $count==0)
{
   $pattern = $pattern ."_". $arrString[$count];
   $count++;
    }
    else break;
 }

 return substr($pattern,1);
}
</code></pre>

<p>This works great - but I wanted to know if there was a more elegant way of doing this using regular expressions?</p>
