Need help with str_replace

Discussion in 'PHP' started by MindBlogger, Sep 4, 2008.

  1. #1
    Hi,

    I have a text file called keywords.txt and I want to search the $text variable for the keywords in the keywords.txt file and replace those kwywords with the <b>,</b> tags to bold them in the output.

    This is the piece of code I wrote.

    everything works fine, except that in the output, only the last keyword specified in the keywords.txt file gets bolded. I've tried different loop techniques and methods to get all the keywords in the txt file to be bolded - still no luck.

    So I guess the problem is logical. Any help is appreciated.
    Thanks!
     
    MindBlogger, Sep 4, 2008 IP
  2. Joseph S

    Joseph S Well-Known Member

    Messages:
    1,373
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    155
    #2
    Try this:


    <?php
    $handle = @fopen(ABSPATH."wp-content/plugins/keywords.txt", "r");
    if ($handle) {
       while (!feof($handle)) {
           $buffer = fgets($handle, 4096);
           echo "<b">$buffer</b>, ";
       }
       fclose($handle);
    }
    ?>
    Code (markup):
     
    Joseph S, Sep 4, 2008 IP
    MindBlogger likes this.
  3. JEET

    JEET Notable Member

    Messages:
    3,832
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #3
    Try this:
    $c= file_get_contents('keywords.txt');
    preg_replace('/['.$text.']/', '<b>'.$text.</b>',$c);
    I'm not very good with pregs, but I think the above will work. :)
     
    JEET, Sep 4, 2008 IP
    MindBlogger likes this.
  4. Shoro

    Shoro Peon

    Messages:
    143
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    My guess is that there's some kind of whitespace or other character(s) preventing the other lines from matching. Try inserting a $line = trim($line); before the str_replace line.
     
    Shoro, Sep 4, 2008 IP
    MindBlogger likes this.
  5. MindBlogger

    MindBlogger Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thank you all for your wonderful support. I tried all of your suggestions and...

    Shoro, thanks a lot! That worked. The prob was in the whitespace.
     
    MindBlogger, Sep 4, 2008 IP
  6. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Almost, you need to remove the [ ] completely and it will work fine. if you were to use braces, it would be ( ) instead
     
    JAY6390, Sep 5, 2008 IP