Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Feb 2009
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    preg_replace - ignore long words

    I am working with the following preg_replace code:

    Code:
    $text = preg_replace("|($word)|Ui" , "[h]$1[/h]" , $text );
    It applies highlighting [h]..[/h] 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.
    Last edited by Tafalezono; 03-21-2009 at 03:21 PM.

  • #2
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,517
    Thanks
    114
    Thanked 110 Times in 109 Posts
    why not just not run the preg_replace if the size of $text is greater than 15

    PHP Code:
    if(strlen($text))<15)
    {
         
    $text preg_replace("|($word)|Ui" "[h]$1[/h]" $text );

    Or is it homework?
    You can not say you know how to do something, until you can teach it to someone else.

  • #3
    New Coder
    Join Date
    Feb 2009
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts
    But what if $text = "chickensoup chickensoupfortoday"

    the function would then need to return:

    [h]chicken[/h]soup chickensoupfortoday

  • #4
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,517
    Thanks
    114
    Thanked 110 Times in 109 Posts
    Then I would do

    PHP Code:
    <?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" "[h]$1[/h]" $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...
    You can not say you know how to do something, until you can teach it to someone else.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •