dogfighter Posted November 28, 2009 Share Posted November 28, 2009 I'm trying to replace words in paragraphs with random words from a database (a-la madlib), but I don't want it to grab partial words. For example, I want it to replace "white" and not part of "whiten" or "whitest". I'm thinking the way to do this is to define individual words as the word preceded by a space and followed by either another space or some form of punctuation...so: " white " " white." " white!" I know this will miss the first word in a paragraph since there's usually not a space before it, but I can live with that. The problem is I don't want to do preg_replace 15 different times just to get all instances. And I also want the replace to use the following character... so a match on " white!" should be replaced with " black!" and not " black ". Here's the code I have so far, mostly borrowed from a free example I found online: <?php function spin($text) { //While there's pairs of square brackets, spin whats inside of them while (!(strpos($text,'[') === FALSE) && !(strpos($text,']') === FALSE)) { //Find the first '[' $leftb = strpos($text,'['); //Find the first ']' $rightb = strpos($text,']'); //Split the string up, then (psudo)randomise the item chosen $spintext = split(',',substr($text,$leftb+1,$rightb-$leftb-1)); $spinselect = trim($spintext[mt_rand(0,count($spintext)-1)]); //Get the whole string to replace including the brackets $brackettext = substr($text,$leftb,($rightb-$leftb)+1); //Replace the [blah,blah2] with whatever item is chosen $text = str_replace($brackettext,$spinselect,$text); } //return the block of modified text return $text; } $tospin = "The quick brown fox."; $patterns[0] = '/ quick /'; $patterns[1] = '/ brown /'; $patterns[2] = '/ fox /'; $replacements[0] = '[ fast , sluggish, speedy ]'; $replacements[1] = '[ pink , white , yellow , blue ]'; $replacements[2] = '[ bear , snake , bird ]'; ksort($patterns); ksort($replacements); $prespin = preg_replace($patterns, $replacements, $tospin); echo spin($prespin); ?> Can anyone help me with this? I'm a bit out of my league with this one.. Quote Link to comment Share on other sites More sharing options...
thebadbad Posted November 28, 2009 Share Posted November 28, 2009 Word boundaries were made just for this. Example: <?php $str = 'The whitest color is white.'; echo preg_replace('~\bwhite\b~i', 'black', $str); ?> Quote Link to comment Share on other sites More sharing options...
dogfighter Posted November 28, 2009 Author Share Posted November 28, 2009 beautiful, thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.