robimy seo robimy seo - 2 months ago 10
PHP Question

Put something in article in random place with PHP

I am trying to put random text in an article so I use

explode
to make every word an array:

$article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';

$words = explode(' ', $article);
// a new array to hold the string we are going to create
$newString = array();
// loop all words of the original string
foreach ($words as $i => $w) {
// add every word to the new string
$newString[] = $w;
}

$inserted = array('ad this in random place'); // Not necessarily an array
$ilejest = count($newString); // count all words from array
$wstawwloowo = rand(1, $ilejest); // random number from 1 to max number of values in array
$newString = array_splice( $newString, $wstawwloowo, 0, $inserted ); //

// create a string from the array of words we just composed
$contenttre = implode(' ', $newString);


How to make it works?

Answer
  $article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';

  $words = explode(' ', $article);
                    // a new array to hold the string we are going to create
  $randId = rand(0, sizeOf($words));
  array_splice($words, $randId, 0, array('Random string in random place'));
  $newString = implode(',', $words);
  echo $newString; // Will print the new string

Hope this helps !

Demo : http://www.tutorialspoint.com/execute_php_online.php?PID=0Bw_CjBb95KQMcmE0V1hnR0lCV2s