reg_replace - ignore long words

Discussion in 'PHP' started by Tafalezono, Mar 21, 2009.

  1. #1
    I am working with the following preg_replace code:

    $text = preg_replace("|($word)|Ui" , "[h]$1[/h]" , $text );
    Code (markup):
    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.
     
    Tafalezono, Mar 21, 2009 IP
  2. NatalicWolf

    NatalicWolf Peon

    Messages:
    262
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    maybe reg ex isnt the best method? Perhaps using raw PHP code to split the data then apply the formatting...
     
    NatalicWolf, Mar 21, 2009 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    "|($word){1,15}|Ui"
     
    jestep, Mar 24, 2009 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Actually, I think you would need to do this assuming your regex already works.

    if(strlen($word) < 15){

    $text = preg_replace("|($word)|Ui" , "[h]$1[/h]" , $text );

    }
     
    jestep, Mar 24, 2009 IP
  5. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #5
    Because $word itself will have a variable length, a pattern would be too complicated.

    Keep it simple and use preg_replace_callback instead so you can check the length within the callback function and react to it there.
     
    joebert, Mar 24, 2009 IP