Search code examples
phpregexmatchstrpos

how to check if date and string exist in text file


I have a php function to log users:

if(isset($_POST['enter'])){
if($_POST['name'] != "" && trim($_POST['name'])!= "" ){
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
        
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> </div>";
file_put_contents("users.html", $text_message, FILE_APPEND | LOCK_EX);

It's working fine, just if someone is refreshing the page, the "file_put_contents" function will log again.

So i'm trying to avoid duplicates:

$chck = file_get_contents("users.html");
if (false === strpos($chck, date("F j, g").' '.$_SESSION['name']){
  //file_put_contents
}

I want to check for date - only date and hour (not minutes) and the username. As i'm using 12h time, how can i check for PM and AM ?

Output:

January 18, 7:33 AM username
January 18, 7:41 AM username

January 18, 7:45 AM username

For simplifying: i want to check for "January 18," "7" "AM" "username".


Solution

  • The sequence date("F j, g").' '.$_SESSION['name'] cannot exists, because there are some characters between the date and the user name.

    You could check use a simple regular expression like "January 18, 9:[0-9]{2} AM"

    $date = date('F j, g:[0-9]{2} A');
    $match = preg_match('~' . $date . '~', $text_message);
    
    if (strpos($text_message, $_SESSION['name']) === false && !$match) {
        echo "match not found";
        // file_put_contents()
    }
    else {
        echo "match found";
    }