PHP Better way to Replace/Match $1
<p>I am trying to replace <code>$1, $2, $3</code> variables in a URL with another URL.
You can copy paste my example below and see my solution. </p>

<p>But I feel like there is a more elegant way with an array mapping type function or a better preg_replace type of thing. I just need a kick in the right direction, can you help?</p>

<pre><code>    &lt;?php
    /**
    *  Key = The DESIRED string
    *  Value = The ORIGINAL value
    *
    * Desired Result: project/EXAMPLE/something/OTHER
    */
    $data = array(
        'project/$1/details/$2' =&gt; 'newby/EXAMPLE/something/OTHER'
    );

    foreach($data as $desiredString =&gt; $findMe)
    {
        /**
        * Turn these URI's into arrays
        */
        $desiredString = explode('/', $desiredString);
        $findMe = explode('/', $findMe);

        /**
        * Store the array position of the match
        */
        $positions = array();
        foreach($desiredString as $key =&gt; $value) {
            /**
            * Look for $1, $2, $3, etc..
            */
            if (preg_match('#(\$\d)#', $value)) {
                $positions[$key] = $value;
            }
        }

        /**
        * Loop through the positions
        */
        foreach($positions as $key =&gt; $value){
            $desiredString[$key] = $findMe[$key];
        }

        /**
        * The final result
        */
        echo implode('/', $desiredString);
    }
</code></pre>
