Home > Back-end >  Regular expression in PHP to detect extra/missing space in parenthesis
Regular expression in PHP to detect extra/missing space in parenthesis

Time:03-13

Assume the texts below:

(this is ) a ( text ) with(some) parenthesis(errors)

I am trying to write a PHP regular expression to detect grammar errors in parenthesis, in particular spaces. The correct text here is:

(this is[no space]) a ([no space]text[no space]) with[missing space](some) parenthesis[missing space](errors)

note that I do not want to correct it, but just to return true/false and the function should be multibyte safe.

My current code looks like this but it does not work.

    $r = mb_ereg_match("\(\s\S", trim($str));
    $r = $r | mb_ereg_match(".\S\(", trim($str));
    $r = $r | mb_ereg_match("\)\S", trim($str));
    $r = $r | mb_ereg_match(".\S\s\)", trim($str));

CodePudding user response:

Using preg_match we can try:

$text = "(this is ) a ( text ) with(some) parenthesis(errors)";
if (preg_match("/\(\s [^)] \)|\([^)] \s \)|\w\(|\)\w/", $text)) {
    echo "invalid grammar detected";
}
  •  Tags:  
  • php
  • Related