Regex help - matching entire words.

Discussion in 'PHP' started by blueparukia, Jun 8, 2008.

  1. #1
    I wanna match the word "hello" - case insensitive.

    But it has to be the word "hello" by itself, not "hellos" or "sfhello".

    And I want to use preg replace, so that the hello is the $1 variable.

    Poor explanation, I know, but I don't how else to explain. Should be relatively simple for those people who actually like regex.
     
    blueparukia, Jun 8, 2008 IP
  2. live-cms_com

    live-cms_com Notable Member

    Messages:
    3,128
    Likes Received:
    112
    Best Answers:
    0
    Trophy Points:
    205
    Digital Goods:
    1
    #2
    hello|Hello would do it, I think.
     
    live-cms_com, Jun 8, 2008 IP
  3. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #3
    You'd think so.

    My code:

    
    
    $var = "sfahellos";
    
    $funcs="hello|test";
    
    $result = preg_replace("~($funcs)~si","<span style='color:#00F;font-weight:bold'>$1</span>",$var);
    
    
    PHP:
    The problem is, the hello is still turning blue, which I don't want - unless $var equalled "hello" exactly.

    As $var equals "sfahellos", it shouldn't do anything.

    Cheers,

    BP
     
    blueparukia, Jun 8, 2008 IP
  4. live-cms_com

    live-cms_com Notable Member

    Messages:
    3,128
    Likes Received:
    112
    Best Answers:
    0
    Trophy Points:
    205
    Digital Goods:
    1
    #4
    ^hello|test$ works if your input is only one word. If you wanted to do it in a sentence you'd need to have spaces in your string.
     
    live-cms_com, Jun 8, 2008 IP
  5. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #5
    I need to do it without spaces. And I've seen it done before, so I know its possible....

    Thanks anyway.
     
    blueparukia, Jun 8, 2008 IP
  6. lui2603

    lui2603 Peon

    Messages:
    729
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #6
    /^hello$/i

    ??
     
    lui2603, Jun 8, 2008 IP