SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict adam2003w's Avatar
    Join Date
    Mar 2004
    Location
    colorado
    Posts
    396
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    php preg_match alternative (finding keyword and surrounding words in a string)

    I'm trying to find a keyword (ex. "dog bone") in a paragraph string (ex. "I bought my lucky dog a new dog bone and he loves it." using PHP preg_match & preg_replace. I found some code (from early 2000s) that works ok but is slow.

    Anyone know of a good alternative or better way to write this code?

    PHP Code:
    $tmp "dog bone"
    $string "I bought my lucky dog a new dog bone and he loves it."

    preg_match("/(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?$tmp? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)?/i"$string$result);

    if (
    $result[0] != "") {
    $my_output preg_replace("/$tmp/i","<B>$tmp</B>",$result[0]);
    }

    echo 
    $my_output

  2. #2
    SitePoint Addict adam2003w's Avatar
    Join Date
    Mar 2004
    Location
    colorado
    Posts
    396
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I found a way to speed up the process (though the code is much longer).

    It has to do with breaking up the string by word into an array then doing an array search for the keyword(s).

    It takes too long to explain but this page helped me out a lot.
    http://stackoverflow.com/questions/4...php-preg-match

  3. #3
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,154
    Mentioned
    14 Post(s)
    Tagged
    0 Thread(s)
    That regexp pattern seems awfully convoluted. This should be all you need.

    $my_output = preg_replace("/($tmp)/i", "<b>$1</b>", $string);

    In fact, you may not need a regexp at all.

    $my_output = str_replace($tmp, "<b>$tmp</b>", $string);
    "First make it work. Then make it better."


Bookmarks

Posting Permissions

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