2014-10-05 4 views
3

하드 코딩 된 단어 목록에서 임의로 구문을 생성하는 함수를 만들었습니다. 함수를 get_words() 하드 코드 된 단어 문자열을 다음 배열을 차례로 셔플 및 반환합니다.PHP : 문자열 인덱싱 불일치?

get_words()generate_random_phrase() 의해 호출되는 get_words() n 회를 반복하고, 모든 반복들이 사용자에게 리턴 될 운명 최종 구문에 해당 단어에 연접.

제 문제는, PHP가 일관성없는 결과를 계속 제공한다는 것입니다. 그것은 나에게 무작위로 주어진 단어를 주지만 일관성없는 단어 수를줍니다. 4 단어를 기본값으로 지정하고 4 단어 대신 1-4 단어 사이의 구문을 제공합니다.이 프로그램은 매우 간단하므로 정확한 문제를 정확하게 지적 할 수 없습니다. 체인의 끊어진 링크가 색인되는 $words 배열 인 것 같습니다. 어떤 이유로 색인 생성이 실패하는 것처럼 보입니다. 나는 PHP에 익숙하지 않다. 누군가 나에게 설명 할 수 있을까? 당신은 또한 배열 내부 공간을 포함하기 때문에

<?php 

function generate_random_phrase() { 
    $words = get_words(); 
    $number_of_words = get_word_count(); 
    $phrase = ""; 
    $symbols = "[email protected]#$%^&*()"; 
    echo print_r($phrase); 

    for ($i = 0;$i < $number_of_words;$i++) { 
    $phrase .= " ".$words[$i]; 
} 


    if (isset($_POST['include_numbers'])) 
    $phrase = $phrase.rand(0, 9); 

    if (isset($_POST['include_symbols'])) 
    $phrase = $phrase.$symbols[rand(0, 9)]; 

    return $phrase; 
} 

function get_word_count() { 
    if ($_POST['word_count'] < 1 || $_POST['word_count'] > 9) 
    $word_count = 4; #default 
    else 
    $word_count = $_POST['word_count']; 
    return $word_count; 
} 

function get_words() { 
    $BASE_WORDS = "my sentence really hope you 
    like narwhales bacon at midnight but only 
    ferver where can paper laptops spoon door knobs 
    head phones watches barbeque not say"; 
    $words = explode(' ', $BASE_WORDS); 
    shuffle($words); 
    return $words; 
} 
?> 

답변

2

탭과 새로운 라인이 왜 폭발 한 배열의 공간을 점유하고 있습니다 : 여기

는 수정 된 버전입니다. 개행과 탭을 제거하면 정답이 생성됩니다. 즉 :

$BASE_WORDS = "my sentence really hope you like narwhales bacon at midnight but only ferver where can paper laptops spoon door knobs head phones watches barbeque not say"; 
+0

와우, 당신의 천재 : 여기

은 수정입니다! 감사 –

2

귀하의 기능이 조금 일관성이 보인다, 당신이 그들을 포함 할 때, 당신은 5 개 단어 (하나 개의 공간 인덱스 4 개 진짜 단어 것으로 보인다 루프,에 포함하는 이유 이잖아)가 실제로 올바르지 않습니다. 공백을 포함하여 먼저 공백을 필터링 할 수도 있습니다. 그래서 때 루프를,이 경우, 공백을 포함

Array 
(
    [0] =>    // hello im a whitespace, i should not be in here since im not really a word 

    [1] => but 
    [2] => 
    [3] => bacon 
    [4] => spoon 
    [5] => head 
    [6] => barbeque 
    [7] => 
    [8] => 
    [9] => sentence 
    [10] => door 
    [11] => you 
    [12] => 
    [13] => watches 
    [14] => really 
    [15] => midnight 
    [16] => 

:

여기에 무슨 뜻인지의 시각적 표현입니다. 만약 당신이 5이라는 단어를 가지고 있다면, 그 5 단어를 얻지 못합니다. index 0 - 4 3 (1 => but, 3 => bacon, 4 => spoon)처럼 보일 것입니다.

$ BASE_WORDS에서
function generate_random_phrase() { 
    $words = get_words(); 
    $number_of_words = get_word_count(); 
    $phrase = ""; 
    $symbols = "[email protected]#$%^&*()"; 
    $words = array_filter(array_map('trim', $words)); // filter empty words 
    $phrase = implode(' ', array_slice($words, 0, $number_of_words)); // no need for a loop 
    // this simply gets the array from the first until the desired number of words (0,5 or 0,9 whatever) 
    // and then implode, just glues all the words with space 
    // so this ensure its always according to how many words you want 

    if (isset($_POST['include_numbers'])) 
    $phrase = $phrase.rand(0, 9); 

    if (isset($_POST['include_symbols'])) 
    $phrase = $phrase.$symbols[rand(0, 9)]; 

    return $phrase; 
} 
0

단어 목록에 불일치가있는 간격이 문제입니다.

function get_words() { 
    $BASE_WORDS = "my|sentence|really|hope|you| 
|like|narwhales|bacon|at|midnight|but|only| 
|ferver|where|can|paper|laptops|spoon|door|knobs| 
|head|phones|watches|barbeque|not|say"; 
    $words = explode('|', $BASE_WORDS); 
    shuffle($words); 
    return $words; 
}