PHP实现字符串长单词处理:替换长度≥6单词后续字符为*
解决长单词替换问题的两种方法
别担心,我来帮你搞定这个需求!要实现查找字符串中长度≥6的单词,并把第6个字符之后的内容替换成*,有两种常用的思路,我都给你列出来:
方法一:用正则回调直接处理字符串(最简便)
这种方法不用手动遍历数组,直接用preg_replace_callback就能批量处理所有符合条件的单词,还能自动避开标点符号,不会把逗号、句号这类符号当成单词的一部分:
$a = 'The game is set in "The City", a dark fantasy world inspired by Victorian, Gothic, and steampunk aesthetics. Players control Garrett, a master thief who embarks on several missions focusing on stealing from the rich. Players may approach levels in a variety of different ways...'; // 处理长单词的回调函数 $result = preg_replace_callback('/\b(\w+)\b/', function($matches) { $word = $matches[1]; // 判断单词长度是否≥6 if (strlen($word) >= 6) { // 保留前5个字符,后面的每个字符替换成* return substr($word, 0, 5) . str_repeat('*', strlen($word) - 5); } // 短单词直接返回原内容 return $word; }, $a); // 输出处理后的结果 echo $result;
运行后你会看到类似这样的输出:
The game is set in "The City", a dark fanta** world inspi** by Victo****, Gothic, and steam*** aesthe****. Playe* contr* Garre*, a maste* thief who embar* on sever* missi**** focus*** on steal* from the rich. Playe* may approa* levels in a variety of differ**** ways...
方法二:手动遍历拆分后的数组(适合理解过程)
如果你确实想手动遍历$parts数组,我们可以先把字符串拆分成「单词」和「非单词(标点、空格等)」两部分,再逐个处理:
$a = 'The game is set in "The City", a dark fantasy world inspired by Victorian, Gothic, and steampunk aesthetics. Players control Garrett, a master thief who embarks on several missions focusing on stealing from the rich. Players may approach levels in a variety of different ways...'; // 拆分字符串,保留单词和非单词分隔符 $parts = preg_split('/(\W+)/', $a, -1, PREG_SPLIT_DELIM_CAPTURE); $result = ''; // 遍历每个拆分后的元素 foreach ($parts as $part) { // 只处理纯字母数字的单词 if (ctype_alnum($part)) { if (strlen($part) >= 6) { $part = substr($part, 0, 5) . str_repeat('*', strlen($part) - 5); } } // 把处理后的元素拼回去 $result .= $part; } echo $result;
这个方法的好处是能清晰看到每一步的处理过程,拆分后的$parts数组会包含像["The", " ", "City", ", ", ...]这样的元素,我们只对纯单词部分做替换,其他内容原样保留。
小说明
- 这里的「单词」定义为纯字母数字(用
\w+和ctype_alnum判断),如果你的字符串里有带连字符或 apostrophe 的单词(比如don't),可以调整正则表达式,比如把\w+改成[\w'-]+来适配。 - 替换规则是保留前5个字符,后面的每个字符都换成*,如果想不管后面有多少字符都只加一个*,把
str_repeat('*', strlen($word) - 5)改成'*'就行。
内容的提问来源于stack exchange,提问作者Anna Kurmanova
相关产品推荐
相关产品推荐

