开发者

Need help with a PHP preg_match

开发者 https://www.devze.com 2022-12-21 05:37 出处:网络
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)

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.


try this as your pattern:

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

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号