在字符串php

时间:2018-03-27 11:36:33

标签: php arrays string loops

我需要在length >= 6的字符串中找到单词,并用*替换第6个字符后面的任何字符。

似乎很困惑如何遍历$ parts数组来查找这6个字母的单词。

有人可以帮忙吗?

$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; players 
can choose the action oriented and lethal approach, where players will 
disable or kill enemies on their way to their destination, using knives and 
takedowns, or opt for the non-lethal stealthy approach, where players 
minimize interaction with NPCs and the environment in order to avoid 
detection. Players also may choose which path to take to their destination, 
as each location contains several branching paths.';

$length = 6;

$parts = explode(' ',$a);

然后

for ($i = 0; $i == $length; $i++){
    echo str_replace($parts, '*', $a);
}

1 个答案:

答案 0 :(得分:2)

您可以使用preg_replace_callback()使用正则表达式来转换长度为6个字符或更长的单词。在回调中,使用substr()替换以获取6个第一个字符,并根据需要追加*以获取单词的大小。

$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; players
can choose the action oriented and lethal approach, where players will
disable or kill enemies on their way to their destination, using knives and
takedowns, or opt for the non-lethal stealthy approach, where players
minimize interaction with NPCs and the environment in order to avoid
detection. Players also may choose which path to take to their destination,
as each location contains several branching paths.';

$a = preg_replace_callback('~\b\w{6,}\b~', function($matches) {
  // return the 6 first characters as clean, and the rest with *
  return substr($matches[0], 0, 6) . str_repeat('*', strlen($matches[0]) - 6);
}, $a);
echo $a ;

输出:

The game is set in "The City", a dark fantas* world inspir** by
Victor***, Gothic, and steamp*** aesthe****. Player* contro* Garret*, a
master thief who embark* on severa* missio** focusi** on steali** from the
rich. Player* may approa** levels in a variet* of differ*** ways; player*
can choose the action orient** and lethal approa**, where player* will
disabl* or kill enemie* on their way to their destin*****, using knives and
takedo***, or opt for the non-lethal stealt** approa**, where player*
minimi** intera***** with NPCs and the enviro***** in order to avoid
detect***. Player* also may choose which path to take to their destin*****,
as each locati** contai** severa* branch*** paths.

正则表达式:

\b     # wordboundary
\w{6,} # letter of 6 or more length
\b     # wordboundary