how to replace numbers from string so that they match proper number only not their sub numbers?

I am beginner for regular expression. so facing following problem.

my code is as follows.

Read More
$originalStr="101 abc 1101 xyz";
preg_match_all('/[0-9]{3,5} /', $originalStr, $matches);
$result=array();
$result=array_unique($matches[0]);
sort($result);
global $wpdb;
for($i=0;$i<count($result);$i++)
{   

    $getName="SELECT Name FROM MyTable WHERE ProductID='".trim($result[$i])."' LIMIT 1";
    $data = $wpdb->get_results($getName);
    $replaceWith="";
    foreach ($data as $obj)
    {
        $replaceWith=$obj->Name;
        $originalStr=str_replace($result[$i], $result[$i]." : ".$replaceWith, $originalStr);        
        break;      
    }   
}
echo $originalStr;

here my purpose is to replace product id by ‘product id : product Name’ but the problem is that as 1101 is having 101 as its sub number so it is replacing it 1101’s string with also 101’s string.

so i am getting array of numbres fine but my problem is with replacement. I want it to be replaced with exact numbermatch only.

Related posts

Leave a Reply

2 comments

  1. You could use preg_replace_callback instead of manually looping over the result list and replacing it in a second step (with str_replace not being aware of context or which one to replace).

     $newStr = preg_replace_callback('/([0-9]{3,5}) /', "cb_repl", $originalStr);
    
     function cb_repl($match) {
         list ($all, $num) = $match;
    
         db("SELECT Name FROM MyTable WHERE ProductID='$num' LIMIT 1");
         ...
    
         return "{$num} : {$replaceWith} ";   // just the replacement string
     }
    

    So just do your database query in the callback. It’s not super efficient to do multiple queries in a loop, nor in that callback. But it’s easier at least. And preg_replace_callback knows exactly which part it matched and replaces this exact substring with the returned replacement.