2011-05-29 18 views
3

這是我目前的php腳本。如何確定計數並從結果中隨機編輯?

$mystr = 'Hello world. The world is nice'; 
substr_count($mystr, 'world'); // count=2; 
$mytext = preg_replace('/\b('.$mystr.')\b/i', '<b>$1</b>', $mytext); 

我想隨機將這個單詞中的一個以粗體顯示。 有什麼聰明的方法嗎? THX先進,史蒂芬

+1

你想讓'世界'事件之一是大膽的,或_any_一個字? – Dogbert 2011-05-29 11:05:20

回答

0

你試圖使一個特定的詞,即world大膽?如果是的話,一個方法可能是:

function make_bold($str, $replace) { 
    $words = array_intersect(str_word_count(strtolower($str), 2), $replace); 
    if(count($words) > 0) { 
     $rand_pos = array_rand($words); 
     $str = substr_replace($str, '<b>' . $words[$rand_pos] . '</b>', $rand_pos, strlen($words[$rand_pos])); 
    } 
    return $str; 
} 

用作:

$str = make_bold($str, array('world')); 

參考:str_word_countarray_intersectarray_randsubstr_replace

觀看DEMO

0
$mystr = 'Hello world. The world is nice'; 
$words = explode(' ', $mystr); 
$randWordKey = rand(0, count($words)); 
$words[$randWordKey] = '<b>' . $words[$randWordKey] . '</b>'; 
$mytext = implode(' ', $words);