简体   繁体   中英

How I can validate the syntax of if statement using regex in php

I have a string input, and I want to check if this string contains the correct syntax of if statement. And extract every part of it.

String Format:

if(D1[Condition]D2)str1:str2

" if " should not be case sensitive
D1 And D2 should be numbers
Condition should be one of the following > < >= <= == !=

string examples:

$example   = "if(54>52)14:0";
$example   = "If(54==52)dsfd:fsde";  

I used this regex but I'm not good at using regex and I don't know if it's good or not.

if\(\d+(==|<=|>=|>|<|!=)\d+\).+:.+

I want to extract D1 ,D2 ,Condition , str1 , str2

try this!

^if\((\d+)(>|<|>=|<=|==|!=)(\d+)\)(\w{1,50})\:(\w{1,50})

https://regex101.com/r/qZ7oM7/2

This regex should work:

/^if\(\d+([<>=!]=|[<>])\d+\).{1,50}:.{1,50}$/i

This insensitively matches if( , then digits, then any or your operators, then digits, then ) , then a string of maximum 50 characters, then : , then a string of maximum 50 characters.

Here you have it

/^If\s*\((\d+)\s*(==|<=|>=|>|<|\!=)\s*(\d+)\)\s*(\w{1,50})\:(\w{1,50})$/i

https://regex101.com/r/jR0bO1/1

I already added optional spaces in some places which you can add even more before and after other parenthesis. \\w doesn't allow spaces in the strings. You can replace them with . to allow anything you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM