Take the 2-minute tour ×

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

my code is as follows.

$originalStr="101 abc 1101 xyz";
preg_match_all('/[0-9]{3,5} /', $originalStr, $matches);
global $wpdb;

    $getName="SELECT Name FROM MyTable WHERE ProductID='".trim($result[$i])."' LIMIT 1";
    $data = $wpdb->get_results($getName);
    foreach ($data as $obj)
        $originalStr=str_replace($result[$i], $result[$i]." : ".$replaceWith, $originalStr);        
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.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
Hey Great thanks. It worked. –  Dena Jan 27 '12 at 9:43
add comment

maybe change your regexp to something like this /(^|\s)[0-9]{3,5} /

share|improve this answer
add comment

Your Answer


