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);
$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.
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).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.maybe change your regexp to something like this
/(^|s)[0-9]{3,5} /