0

I am trying to find a php preg_match that can match

test1 test2[...] but not test1 test2 [...]

and return test2(...) as the output as $match.

I tried

preg_match('/^[a-zA-Z0-9][\[](.*)[\]]$/i',"test1 test2[...]", $matches);

But it matches both cases and return the full sentence.

Any help appreciated.

2
  • 2
    More details on the example please! Commented Nov 19, 2009 at 1:08
  • Is "test1 test2[...] but not test1 test2 [...]" a string or an array? Commented Nov 19, 2009 at 1:15

1 Answer 1

2
preg_match('/([a-zA-Z0-9]+[\[][^\]]+[\]])$/i',"test1 test2[...]", $matches);

notice the + after [a-zA-Z0-9] it says one or more alpha numeric character

the ( and ) around the whole expression would permit you to catch the whole expression.

Since your content is around [] I have changed .* to [^\]] since the regular expression are greedy in case of test2[.....] test3[sadsdasdasdad] it would capture until the end since there is a ].

Also please note since you are using the $ it will match always things in the end, I am not really sure if it's what you intend to do.

You can see this for reference.

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

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.