How to determine the counter and edit a random result?

this is my current php script.

$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 a random word to be in bold. Is there any smart way? thanks in advanced Stephen

+3
source share
2 answers

You are trying to make a specific word, i.e. worldbold? If yes, then 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'));

Link: str_word_count , array_intersect, array_rand,substr_replace

Take a look DEMO .

0
source
$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
source

All Articles