-3

これが私の問題です。特定の単語にランダムな文字を挿入するphp関数を作成したいと思います。

例 :

ランダムな文字 : a、i、u、e、o

特定の言葉 : 猿、鹿、虎、ネズミ

文 : 鹿を食べるトラ、遠くから見るサルとネズミ

文は次のようにしてほしい。

デューアーを食べるトラ、サル、ラットを遠くから見る

4

2 に答える 2

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 で利用可能な関数のアイデアを提供するのに役立つことを願っています。

幸運を!

于 2012-07-05T09:15:29.413 に答える
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;

?>
于 2012-07-05T09:23:20.043 に答える