这是我的问题,我想制作一个 php 函数来向特定单词插入一些随机字母。
例子 :
随机字母:a,i,u,e,o
具体词:猴、鹿、虎、鼠
一句话:虎吃鹿,猴鼠远观
我希望句子是这样的:
老虎吃杜尔,猴子和老鼠从远处看
这是我的问题,我想制作一个 php 函数来向特定单词插入一些随机字母。
例子 :
随机字母:a,i,u,e,o
具体词:猴、鹿、虎、鼠
一句话:虎吃鹿,猴鼠远观
我希望句子是这样的:
老虎吃杜尔,猴子和老鼠从远处看
$sentence = 'a tiger eating a deer, monkeys and rats see from a distance'; // You'll need to load the string into a variable, obviously.
$randomLetterArray = array('a', 'e', 'i', 'o', 'u'); // It's good to set the random letters inside an array so that they can be randomly picked by randomizing the index number.
$specificWordArray = array('monkey', 'deer', 'tiger', 'mouse'); // Words to be altered in an array to easily iterate through.
foreach ($specificWordArray as $specificWord) // Iterating through each of the words to be altered.
{
$indexOfWord = rand(0, strlen($specificWord)-1); // Getting a random number between 0 and the length (in chars) of the word.
$partOfWord = substr($specificWord, 0 , $indexOfWord); // Getting a part of the word based on the random number created above.
// This is more complex.
// The part of the word created above is concatenated by a random selection of one of the random letters.
// This in turn is concatenated by the remaining letters in the word.
$wordReplacement = $partOfWord.$randomLetterArray[rand(0, count($randomLetterArray)-1)].substr($specificWord, $indexOfWord);
$sentence = str_ireplace($specificWord, $wordReplacement, $sentence); // This replaces the word in the sentence with the new word.
}
echo $sentence;
我希望这能给你一些关于如何解决这个问题的想法,我希望这些评论有助于让你了解 PHP 中可用的函数。
祝你好运!
像这样的东西应该可以工作,但我很确定有一种更快更简单的方法来做到这一点。
# the magic function
function magicHappensHere ( $letters, $words, $sentence ) {
$return = '';
# divide by words
$sentence_words = explode( ' ', $sentence );
foreach ( $sentence_words as $value ) {
# check words
if ( array_search( $value, $words ) ) {
# check 'letter' count
$l_number = sizeof( $letters );
# create a random letter value
$rand_letter = rand( 0, ( $l_number-1 ) );
# create random position to use
$rand_pos = rand ( 0, strlen( $value ) );
# change the actual word
$value = substr_replace( $value, $letters[ $rand_letter ] ,$rand_pos, 0 );
}
$return .= $value . ' ';
}
# print out new string ( w/out last space )
return substr( $return, 0, -1 );
}
# define your 'letters'
$letters = array( 'a', 'i', 'u', 'e', 'o' );
# define your 'words'
$words = array( 'monkey', 'deer', 'tiger', 'mouse' );
# define your 'sentence'
$sentence = 'a tiger eating a deer, monkeys and rats see from a distance';
# change text
$new_sentence = magicHappensHere ( $letters, $words, $sentence );
print $new_sentence;
?>