...

View Full Version : preg_replace - ignore long words



Tafalezono
03-21-2009, 04:14 PM
I am working with the following preg_replace code:


$text = preg_replace("|($word)|Ui" , "$1" , $text );

It applies highlighting .. to all words in $text matching $word

But I don't want it to apply highlighting if the matched word in $text is longer than 15 characters.

Example:
$word = 'chicken';

$text contains:
chickensoup -> 11 characters -> apply highlighting -> chickensoup
chickensoupfortoday -> 19 characters -> don't apply highlighting

I have read somewhere that one can use the curly brackets e.g. {15,} but I am not sure how to use it.

timgolding
03-22-2009, 04:04 PM
why not just not run the preg_replace if the size of $text is greater than 15



if(strlen($text))<15)
{
$text = preg_replace("|($word)|Ui" , "$1" , $text );
}


Or is it homework?

Tafalezono
03-22-2009, 04:32 PM
But what if $text = "chickensoup chickensoupfortoday"

the function would then need to return:

chickensoup chickensoupfortoday

timgolding
03-22-2009, 05:24 PM
Then I would do



<?PHP
$text="chickensoup chickensoupfortoday";
$word="chicken";

$words = explode(" ", $text);
foreach($words as $word_)
{
if(strlen($word_)<15)
{

$new_words[count($new_words)]= preg_replace("|($word)|Ui" , "$1" , $word_ );
}
else
{
$new_words[count($new_words)]=$word_;
}
}

$text=implode(" ", $new_words);
echo $text;
?>


Not saying this is the best way to do it. Mainly cos I am a noob with regex. But it works all the same...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum