如何使用PHP在句子中的特定单词中插入随机字母

时间:2012-07-05 08:47:06

标签: php

这是myproblem,我想制作一个php函数,将一些随机字母插入特定的单词。

示例:

随机字母:a,i,u,e,o

具体词:猴子,鹿,虎,老鼠

句子:老虎吃鹿,猴子和老鼠从远处看

我希望句子是这样的:

从远处看到一个正在吃午餐,monkeiys和raats的朋友

2 个答案:

答案 0 :(得分:2)

$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中可用的功能。

祝你好运!

答案 1 :(得分:0)

这样的事情应该有效,但我很确定有一种更快捷,更简单的方法。     

# 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;

?>