tags:

views:

62

answers:

3

I'm not very good with preg_match so please forgive me if this is easy. So far I have...

preg_match("/".$clear_user."\/[0-9]{10}/", $old_data, $matches)

The thing I'm trying to match looks like..

:userid/time()

Right now, the preg_match would have a problem with 22/1266978013 and 2/1266978013. I need to figure out how to match the colon.

Also, is there a way to match all the numbers until the next colon instead of just the next 10 numbers, because time() could be more or less than 10.

+2  A: 

try this as your pattern:

#:$userId/[0-9]+#

preg_match("#:$userId/[0-9]+#", $old_data, $matches);
removed my answer as it was pretty much the same as yours, except you can use \d+ instead of [0-9]+
Erik
This worked great, thank you! Just so that I can learn preg_match a litter better, what do the # do?
Chris
@Chris The # sign is just a delimiter.
waiwai933
A: 
preg_match("/:*".$clear_user."\/[0-9]{10}/", $old_data, $matches);
ghostdog74
A: 

You need to extend your match and include in your pattern the : delimiter. Failing in doing so lead to the erratic behaviour you already experienced.

By the way, it is not so erratic: take in account the two cases you filed: 22/1266978013 and 2/1266978013. The regex engine matches :2(2/1266978013):(2/1266978013) your pattern two times. If you comprehend the field delimitator (:) you can be shure that only the intended target will be affected.

I would use preg_replace to directly substitute the pattern you found, once you fire the expensive regular expression engine, you should, to me, let it to perform as much work it can.

$pattern='#:'.$clear_user.'/[0-9]{10}#';
$replacement = ":$clear_user/$new_time"
$last_message=preg_replace($pattern, $replacement, $old_data ,-1,$matches);
if (!$matches) {
  $last_message .= $replacement;
}
Eineki