Jump to content

Multiple Patterns for preg_replace


dogfighter

Recommended Posts

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..

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.