check the existence of a string in a text file

Discussion in 'PHP' started by asgsoft, Oct 25, 2007.

  1. #1
    Hi everyone.

    Here is another PHP problem I am faced with.

    is there a way yo check the existence of a string in a text file?

    Thanks
     
    asgsoft, Oct 25, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Yes, but in order to get better help you'd need to be more specific. (examples)

    Here's a basic way to do it:
    
    
    $content = file_get_contents('file.txt');
    
    if (strpos($content, 'your-string') !== false)
    {
        // String was found
    }
    
    
    PHP:
     
    nico_swd, Oct 25, 2007 IP
  3. asgsoft

    asgsoft Well-Known Member

    Messages:
    1,737
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    160
    #3
    Thanks a lot
     
    asgsoft, Oct 25, 2007 IP
  4. asgsoft

    asgsoft Well-Known Member

    Messages:
    1,737
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    160
    #4
    sorry I can't edit the post above but I am having this problem, the first entry is always repeated at the beginning and end.

    domain1.com
    domain2.com
    domain3.com
    domain1.com

    this is the code I am using:
    $content = file_get_contents('domains.txt');
    
    if (strpos($content, $domain) == false){
                $File = "domains.txt";
                $Handle = fopen($File, 'a+');
                $Data = "$domain \n";
                fwrite($Handle, $Data);
                fclose($Handle); 
                }  
    PHP:
    can that be fixed?
     
    asgsoft, Oct 26, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    Do you have each domain in a new line? Try this:
    
    $domains = array_map('trim', file('domains.txt'));
    
    if (!in_array($domain, $domains))
    {
    	file_put_contents('domains.txt', "{$domain}\n", FILE_APPEND);
    }
    
    PHP:
    This will add the domain at the bottom of the text file, if it does not exist there already. I think this is what you want to do?
     
    nico_swd, Oct 26, 2007 IP
  6. asgsoft

    asgsoft Well-Known Member

    Messages:
    1,737
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    160
    #6
    Thats it. It works

    I just had to add \r net to \n to make it add it on a new line. But thats great.
     
    asgsoft, Oct 26, 2007 IP