Chris
Chris

Reputation: 137

Need help with a PHP preg_match

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.

Upvotes: 0

Views: 884

Answers (3)

Eineki
Eineki

Reputation: 14909

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;
}

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342303

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

Upvotes: 0

user262976
user262976

Reputation: 2074

try this as your pattern:

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

preg_match("#:$userId/[0-9]+#", $old_data, $matches);

Upvotes: 2

Related Questions