Search code examples
phppreg-matchfile-get-contentspreg-match-all

How to use preg_match with file_get_contents using PHP?


How to use the preg_match correctly with file_get_content? I have a form that user can login, if the user input a wrong info, the default echo inside file_get_contents will be replace with a new message using preg_match but it's not working.

I have a PHP snippet but I just get only a white blank page.

$reply = file_get_contents($url, false, $context);
if(preg_match($reply, 'No information was found'){
    echo("<script>location.href = '/page/message/';</script>");
} else {
    echo $reply;   
    echo '<div>
   For any other questions please contact us Monday - Sunday 9am - 6pm at <strong style="color: #000;">1235456</strong> or <strong style="color: #000;">info@example.com</strong>
    </div>';
}

Solution

  • For pattern you have to use a delimiter use

    $reply = file_get_contents($url, false, $context);

    if(preg_match('/No information was found/', $reply)){
        echo("<script>location.href = '/page/message/';</script>");
    } else {
        echo $reply;   
        echo '<div>
       For any other questions please contact us Monday - Sunday 9am - 6pm at <strong style="color: #000;">1235456</strong> or <strong style="color: #000;">info@example.com</strong>
        </div>';
    }
    

    Add a / delimiter also preg_match first parameter is pattern you are using pattern in second parameter