刽子手“词”在 PHP 中
我正在尝试做一些类似于刽子手的事情,当你猜测一个字母时,它会用该字母替换下划线。我已经想出了一个方法,但似乎效率很低,我想知道是否有更好的方法。这是我所拥有的 -
<?
$word = 'ball';
$lettersGuessed = array('b','a');
echo str_replace( $lettersGuessed , '_' , $word ); // __ll
echo '<br>';
$wordArray = str_split ( $word );
foreach ( $wordArray as $letterCheck )
{
if ( in_array( $letterCheck, $lettersGuessed ) )
{
$finalWord .= $letterCheck;
} else {
$finalWord .= '_';
}
}
echo $finalWord; // ba__
?>
str_replace
的做法与我想要的相反。我想要 $finalWord
的值,而不必通过循环来获得我想要的结果。
I am trying to do something similar to hangman where when you guess a letter, it replaces an underscore with what the letter is. I have come up with a way, but it seems very inefficient and I am wondering if there is a better way. Here is what I have -
<?
$word = 'ball';
$lettersGuessed = array('b','a');
echo str_replace( $lettersGuessed , '_' , $word ); // __ll
echo '<br>';
$wordArray = str_split ( $word );
foreach ( $wordArray as $letterCheck )
{
if ( in_array( $letterCheck, $lettersGuessed ) )
{
$finalWord .= $letterCheck;
} else {
$finalWord .= '_';
}
}
echo $finalWord; // ba__
?>
str_replace
does the opposite of what I want. I want what the value of $finalWord
is without having to go through a loop to get the result I desire.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我按照你的说法正确,你想要做与第一行相反的事情:
为什么不创建一个
$opposite = range('a', 'z');
数组,然后使用array_diff ()
与 $lettersGuessed 相对应,这将为您提供一组未猜出的字母。它肯定会节省几行代码。例如:If I am following you right you want to do the opposite of the first line:
Why not create an array of
$opposite = range('a', 'z');
and then usearray_diff ()
against $lettersGuessed, which will give you an array of unguessed letters. It would certainly save a few lines of code. Such as:它是一个数组,foreach 是你应该做的事情,无论如何它都快如闪电,我认为你正在沉迷于一些甚至不是问题的东西。
您想要使用数组,因为您可以轻松判断数组中的哪些索引包含该字母,这直接与字符串中 _ 应该成为字母的位置相关。
It's an array, foreach is what you're suppose to be doing, it's lightning fast anyways, I think you are obsessing over something that's not even a problem.
You want to use an array becuase you can easily tell which indexes in the array are the ones that contain the letter, which directly correlates to which place in the string the _ should become a letter.
你的 foreach 循环是一个很好的方法。它不会很慢,因为你的话永远不会很大。
您还可以使用猜测的字母创建正则表达式模式来替换除这些字母之外的所有内容。像这样:
Your foreach loop is a fine way to do it. It won't be slow because your words will never be huge.
You can also create a regex pattern with the guessed letters to replace everything except those letters. Like this:
另一种方法是将字符串作为数组访问,例如
Another way would be to access the string as an array, e.g.