tags:

views:

55

answers:

2

Hey All,

Just wondering if you can help me out with something. I have a string with a series of numbers like 58498, 53980, 84578. Always 5 numbers in the series. Whats the best way to go about removing these?

+3  A: 

You could do it with a regex.

$new_string = preg_replace("/\d{5},?/",'',$string);
Cfreak
Beautiful!!! Works like a charm. Thanks Cfreak!!!!
Tek9
Note that this would also match 6 digits though.
Blair McMillan
@Blair - um ... not it won't {5} is 5 digits and no more. the ,? is to remove trailing commas if they exist.
Cfreak
@Cfreak - Correct, however 123456 would still match, as you don't specify that there cannot be a digit before or after it. Your code would match both (12345)6 as the , is optional and also match 1(23456) as leading digits are allowed. I could have also said that it would match 38 digits.
Blair McMillan
`$new_string = preg_replace("/(^|\s)\d{5}(,?|$)/",'',$string);` would probably be more appropriate. Match the start of the string, or a space, 5 digits and then a comma or the end of the string.
Blair McMillan
+1  A: 

preg_replace (php doc).

You can find the 5-number strings using the pattern: /\d{5}/g and remove each occurrence.

Use it like this:

$string = preg_replace("/\d{5}/g", "", $string); (the g is for global (all occurrences))

If you want to get them (not remove them) then you should use:

preg_match (php doc)

Use it like this:

$matches = array();
preg_replace("/\d{5}/g", $matches);
foreach($matches as $match) {
    // do something with each $match
}
Bob Fincheimer
In PHP (stupidly IMHO) you don't need the g flag because preg_replace replaces all by default.
Cfreak
thanks @Cfreak.
Bob Fincheimer