Page 1 of 1

Preg_replace() , I do missunderstand somthing.

Posted: Fri Feb 22, 2008 4:03 am
by Peec
Hi,

For some time ago i managed to do my first preg_match functions, all was working great until i had to use preg_replace.

I use an compiler on my code, all works but the preg_replace of course.

Code: Select all

 
class NtMacAddress{ 
     
     function getMac(){
         exec("ipconfig /all", $output);
         foreach($output as $line){
             if (preg_match("/(.*)Physical Address(.*)/", $line)){
                 $mac[] = preg_replace("/(.*):/i","lol",$line);
             }
         }
         return $mac;
     }
} 
 
 
echo "MAC: \n\n";
print_r(NtMacAddress::getMac());
 
Im getting some strange output. I only get the original string witch is:

Physical Address . . . . . . . . . . . : XX:XX:XX:XX:XX:XX

It should be: ( lol is there only for testing purposes )
lol XX:XX:XX:XX:XX:XX


Any idea?

I know that my expressions or logic is incorrect @ preg_replace("/(.*):/i","lol",$line);

Re: Preg_replace() , I do missunderstand somthing.

Posted: Sun Feb 24, 2008 12:05 pm
by EverLearning
I got the result you expected(winXP, PHP 5.2.4).

I got the expected output because the format of my MAC address is XX-XX-XX-XX-XX-XX, if it was XX:XX:XX:XX:XX:XX like you said in your post, the result would be:
lol XX
Since regex patterns are 'greedy' by default, regex will match all characters till the last ':'.
To replace text only before the first ':' you have to ungreedy your regex, by adding '?' after the pattern, and limiting the replace count to 1

Code: Select all

$mac[] = preg_replace("/(.*?):/i","lol",$line, 1)
or the result would be:

'lollollollollollolXX'

Maybe you should dump the whole output of 'ipconfig /all' and post it here if you continue having problems.