Home  >  Article  >  Backend Development  >  字符串中替换指定部分字符的问题

字符串中替换指定部分字符的问题

WBOY
WBOYOriginal
2016-06-23 14:20:33904browse

PHP

如果字符串中含有连续数字(14位到19位数字),将连续数字中的倒数第三位至倒数第八位,每一位都替换为一个星号(*)。请问,这个怎么实现?谢了先!


例如:
$str1 = 'test123426789127测试';
//只有12位连续数字,不替换,输出 test123426789127测试

$str2 = '中文736484627347493736';
//替换后输出 中文7364846273******36

$str3 = '号码不是73940128493840571X而是83640148493541398X谢谢!';
//替换后输出 号码不是739401284******71X而是836401484******98X谢谢!

回复讨论(解决方案)

两句完成倒不难,我先想想能否一句完成

$str1 = 'test123426789127测试';//只有12位连续数字,不替换,输出 test123426789127测试$str2 = '中文736484627347493736';//替换后输出 中文7364846273******36$str3 = '号码不是73940128493840571X而是83640148493541398X谢谢!';//替换后输出 号码不是739401284******71X而是836401484******98X谢谢!$p = '/(\d{6,11})\d{5}(\d{2})/';$r = '$1*****$2';echo preg_replace($p, $r, $str1); //test123426789127测试echo preg_replace($p, $r, $str2); //中文73648462734*****36echo preg_replace($p, $r, $str3); //号码不是7394012849*****71X而是8364014849*****98X谢谢!

用断言该如何写?

搞错了,原来中间是定长,还以为不定长,一句可以
preg_replace('#(\D*\d{6,})\d{6}(\d\d\D*)#', '$1******$2', $str)
自己测试

老徐写的好些,除了一点:中间应该是6个数字,

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn