wagh wagh - 6 months ago 23
PHP Question

php Regular expression fails

I'm trying to match string but it is going into last else loop. Can you please provide any help?

$cstg = "<result>True<\/result>";

if (preg_match("/<result>True<\/result>/", $cstg)) {
echo "result success";
}
else if (preg_match("/\<result\>False\<\/result\>/", $cstg)) {
echo "result fail";
}
else {
echo "Something went wrong.";
}

Answer

Issue is coming from your $cstg string. You don't have to escape \ in html text. So following code are working fine:

$cstg = "<result>True</result>";

if( preg_match("/<result>True<\/result>/", $cstg)){
    echo "result success";
}
elseif  (preg_match("/\<result\>False\<\/result\>/", $cstg)){
    echo "result fail";
}else{
    echo "Something went wrong.";
}
Comments