开发者

how to determine count and edit a random from the result?

this is my current php-scrip开发者_C百科t.

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

I want to have randomly one of the word in bold. Is there any smart way? Thx in advanced, Steven


Are you trying to make a specific word, i.e. world bold? If yes, one way could be:

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

used as:

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

Reference: str_word_count, array_intersect, array_rand, substr_replace

Watch a DEMO.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜