Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match returns false

Tags:

php

In the following code why the PHP preg_match returns false? note: I have read some older questions with the same title as my question but the context was different

<html>
    <head>
    </head>
    <body>
        <?php
        $str = "This is a test for PCRE.";
        $ptrn = "This";
        $preg_match_result_arr;
        $preg_match_result = preg_match($ptrn, $str, $preg_match_result_arr);

        if (1 === $preg_match_result)
        {
            echo "The pattern has matched in the string:<br/>".
                "the match is $preg_match_result_arr[0]<br/>";
        }   
        elseif (0 === $preg_match_result) 
        {
            echo "The pattern has not matched in the string:<br/>";
        }
        elseif (false === $preg_match_result)
        {
            echo "An error has occured in matching<br/>";
        }

        ?>
    </body>
</html>
like image 824
MTVS Avatar asked Mar 27 '26 15:03

MTVS


1 Answers

Your expression is not correct, it should be surrounded by delimiters like so.

$ptrn = '/This/';
like image 139
Geoffrey Avatar answered Mar 29 '26 03:03

Geoffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!