easy regex problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kc11
Forum Commoner
Posts: 73
Joined: Mon Sep 27, 2010 3:26 pm

easy regex problem

Post by kc11 »

Hi,

I'm new to regex. I have an array with the elements like so:

Here is my $keys array :


array
'IP:Port' => string '216.114.46.6:3128' (length=17)
'Response Time' => string '0' (length=1)
'Server Speed' => string '0' (length=1)


I would like to replace the ':' with somthing else (like '_' )

here is my regex:

preg_replace('/":"/', "_", $keys);

Its not working. Can anyone show me what I'm doing wrong?

Thanks in advance,

KC
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: easy regex problem

Post by twinedev »

1. You are passing it an array ($keys) instead of a string to process.
2. You telling it to replace quote - colon - quote with an underscore

since you are replacing specific chractersets, you can just use str_replace(), trying something like this:

Code: Select all

foreach($keys as $tKey=>$tValue) {
    $keys[$tKey] = str_replace(':','_',$tValue);
}
-Greg
kc11
Forum Commoner
Posts: 73
Joined: Mon Sep 27, 2010 3:26 pm

Re: easy regex problem

Post by kc11 »

Thanks Greg - That worked!

-KC
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: easy regex problem

Post by McInfo »

The third argument for str_replace() can be an array; so this has the same result.

Code: Select all

$keys = str_replace(':', '_', $keys);
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: easy regex problem

Post by twinedev »

even better! Never realized it could accept an array.
Post Reply