2

I require to match first occurrence of the following pattern starting with \s or ( then NIC followed by any characters followed # or . followed by 5 or 6 digits.

Regular expression used :

preg_match('/[\\s|(]NIC.*[#|.]\d{5,6}/i', trim($test), $matches1);

Example:

  1. $test = "(NIC.123456"; // works correctly
  2. $test = "(NIC.123456 oldnic#65703 checking" // produce result (NIC.123456 oldnic#65703

But it needs to be only (NIC.123456. What is the problem?

2 Answers 2

4

You need to add the ? quantifier for a non-greedy match. Here .* is matching the most amount possible.

You also don't need to double escape \\s here, you can just use \s and you can just combine the selective characters inside your character class instead of adding in the pipe | delimiter.

Also note that your expression will match strings like the following (NIC_CCC.123456, to avoid this you can use a word boundary \b matching the boundary between a word character and not a word character.

preg_match('/(?<=^|\s)\(nic\b.*?[#.]\d{5,6}/i', $test, $match);

Regular expression:

(?<=           look behind to see if there is:
 ^             the beginning of the string
  |            OR
 \s            whitespace (\n, \r, \t, \f, and " ")
)              end of look-behind
\(             '('
 nic           'nic'
 \b            the boundary between a word char (\w) and not a word char
 .*?           any character except \n (0 or more times)
  [#.]         any character of: '#', '.'
  \d{5,6}      digits (0-9) (between 5 and 6 times)

See live demo

Sign up to request clarification or add additional context in comments.

Comments

1

have tried using $test1 = explode(" ", $test); and use $test1[0] to display your result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.