AhaEffect
AhaEffect

Reputation: 1

preg_match php with brackets and determined string is not working

Hi why is the preg_match with brackets and determined string is not working?

Pls let me know your solution to search for "uRole('Admin')".

<?php
    $check ='if(uRole("Admin")||uRole("Design")){';
    
    preg_match('/uRole("Admin")/i', $check)? echo 'match':"";
?>

Upvotes: 0

Views: 46

Answers (2)

Peter van der Wal
Peter van der Wal

Reputation: 11836

That is because the ( and ) is a special character in regular expressions used to create groups.

Because it is a special character, you should use a backslash to escape it:

if (preg_match('/uRole\("Admin"\)/i', $check)) {
    echo 'match';
}

By the way, in this situation a simple stripos is probably more appropriate:

if (stripos($check, 'uRole("Admin")') !== false) {
    echo 'match';
}

Upvotes: 0

Steven
Steven

Reputation: 6148

Two reasons this isn't working...

  1. You have to escape () in REGEX (otherwise it's assuming a group)

  2. You don't use echo in a ternary operator; it has to come before

    echo (STATEMENT_TO_EVALUATE = [TRUE | FALSE]) : TRUE_VALUE : FALSE_VALUE;
    

Working code

$check ='if(uRole("Admin")||uRole("Design")){';
    
echo preg_match('/uRole\("Admin"\)/i', $check, $matches) ? "match" : "";

Upvotes: 1

Related Questions