Home > Enterprise >  Preg for checking how many time it occurs
Preg for checking how many time it occurs

Time:09-21

Here I am having one preg

[-0-9a-zA-Z \/_:.,;=\'{0,2}"{0,2}\s] $

With this I want to check lines whether they contains Alphabets, Numeric and some special character such as - _ , . ; ' " / =. I am getting everything proper but here the issue I faced is with ' & ". Here I want to use this like if quotes are open then it should be closed as well or incase it should not be in use. Either 0 or only 2 times it can be used not more than that.

Example

"hello; max This should not be allowed

"hello; max" This could be allowed if there is no any quotes then also it should allow.

'hello; max' This should be allowed

hello; max This should be allowed

CodePudding user response:

You can use

^(["']?)[-0-9a-zA-Z\/_:.,;= ] \1$

In PHP:

preg_match('~^(["\']?)[-0-9a-zA-Z/_:.,;= ] \1$~', $text)

Or, since [A-Za-z0-9_] = \w,

preg_match('~^(["\']?)[-\w/:.,;= ] \1$~', $text)

See the regex demo.

Replace the literal space with \s if you need to handle any whitespace.

Details:

  • ^ - start of string
  • (["']?) - Group 1: an optional ' or "
  • [-0-9a-zA-Z\/_:.,;= ] - one or more ASCII letters, digits, /, :, ., ,, ;, = or space
  • \1 - match and consume the same char as in Group 1 at the current location
  • $ - end of string.
  • Related