I am looking for a simple way to substituite words in a php echo... For example I would like to create a sentence but alter choice words at random ( or maybe conditional ) within the sentence. For example I had a sentence... [ Fred | Jane | Paco ] likes the color [ purple | red | green ] best of all. What I am wanting is to get a random result each time... Any ideas?
<? $mystring = "the shape is color"; $color = array("red","yellow","green","blue","orange","purple","cyan"); $shape = array("square","circle","rectangle","oval","triangle","hexagon","octagon"); $mystring = preg_replace("/shape/i",$shape[mt_rand(0,count($shape)-1)],$mystring); $mystring = preg_replace("/color/i",$color[mt_rand(0,count($color)-1)],$mystring); echo $mystring; ?> PHP:
<?php $names = array_flip(array("Fred", "Jane", "Paco")); $colors = array_flip(array("purple", "red", "green")); echo array_rand($names) . " likes the color " . array_rand($colors) . " best of all."; ?> PHP: EDIT:: Not sure if it's the best way to go about things, but it works.
<? function random_sentence_from_arrays( $format, $first, $second, $third ) { return sprintf( is_array( $format ) ? $format[ array_rand( $format ) ] : $format, $first[ array_rand( $first ) ], $second[ array_rand( $second ) ], $third[ array_rand( $third ) ] ); } $names = array( 'Joe', 'livingearth', 'ansi', 'NinjaNoodles' ); $shapes = array( 'square', 'circle', 'triangle', 'oblong', 'elephant' ); $colors = array( 'red', 'orange', 'blue', 'green', 'pink', 'violet' ); $formats = array( '%s once bought a %s %s for a gajillion dollars', '%s is of the opinion that %ss always look best on a %s', 'In some countries guys named %s get shot if they do not carry thier %s socks in a %s box', 'Q: What is %s\'s favourite color ?? A: %s' ); for( $i = 0 ; $i < 10 ; $i ++ ) { printf( "%s<br />", random_sentence_from_arrays( $formats, $names, $colors, $shapes ) ); } ?> PHP: The most random I can be .....