如何使用“preg_replace"隐藏特定帖子或更短的代码? [英] How to hide a particular post with "preg_replace" or shorter code?

查看:30
本文介绍了如何使用“preg_replace"隐藏特定帖子或更短的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHPpreg_replace"或更短的代码隐藏特定帖子?

How to hide a particular post with PHP "preg_replace" or shorter code?

我想显示指定文本的前 5后 5 数字pub-.字符串总是以 pub- 开头,并且序列中总是有 16 个数字.只是数字发生了变化.我想用星号替换中间的 6 位数字.

I want to show the first 5 and last 5 digits after pub- of the specified text. The string always starts with pub- and there are always 16 numbers in the sequence. Only the numbers change. I want to replace the middle 6 digits with asterisks.

$string = "pub-9752787982789258";

echo "pub-" . substr(explode("-", $string)[1], 0, 5) . '******' . substr(explode("-", $string)[1], 11, 5);

结果:

pub-97527******89258

推荐答案

如果你只需要在匹配特定格式的字符串中隐藏中间的子字符串你可以使用

preg_replace('~(?:\G(?!^)|^pub-\d{5}(?=\d*$))\K\d(?=\d{5})~', '*', $string)

请参阅 PHP 演示正则表达式演示.

详情

  • (?:\G(?!^)|^pub-\d{5}(?=\d*$)) - 前一个成功匹配或 pub 的结束- 在字符串的开头,然后是 5 位数字,然后是任何 0+ 数字直到字符串的结尾,然后是
  • \K - 省略目前匹配的文本
  • \d - 匹配任意一位数字
  • (?=\d{5}) - 确保右边有五位数字.
  • (?:\G(?!^)|^pub-\d{5}(?=\d*$)) - end of the previous successful match or pub- at the start of the string and then 5 digits followed with any 0+ digits up to the end of the string and then
  • \K - omits the text matched so far
  • \d - matches any 1 digit
  • (?=\d{5}) - makes sure there are five digits on the right.

这篇关于如何使用“preg_replace"隐藏特定帖子或更短的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆