MTVS
MTVS

Reputation: 2096

PHP preg_match returns false

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>

Upvotes: 2

Views: 4289

Answers (4)

Danon
Danon

Reputation: 2973

You could consider using T-Regx that will throw exceptions for you and will automatically delimiter your pattern:

<?php
    try {
        pattern("This")
            ->match("This is a test for PCRE.")
            ->first(function (Match $match) {
                echo "The pattern has matched in the string:<br/>".
                     "the match is $match<br/>";
            });
    }
    catch (MatchPatternException $e)
    {
        echo "An error has occured in matching<br/>";
    }

or you could do

if (pattern("This")->matches("This is a test for PCRE.")) {
    echo "The pattern has matched in the string:<br/>";
}
else {
    echo "The pattern has not matched in the string:<br/>";
}

Upvotes: 0

Santhiya
Santhiya

Reputation: 351

Give your pattern inside '/pattern/'

For Example:

$ptrn='/^This/'

Upvotes: 2

Geoffrey
Geoffrey

Reputation: 11354

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

$ptrn = '/This/';

Upvotes: 4

jeroen
jeroen

Reputation: 91744

You are missing the delimiters, your pattern should look like (# used but it can be something else):

$ptrn = "#This#";

Upvotes: 3

Related Questions