0

Please I have this line;

preg_match_all('/((\w+)?)/'

But I want to also match this pattern in the same preg_match_all

\S+[\.]?\s?\S*

How can I go about it in PHP

3
  • 1
    What's wrong with alternation? BTW, [\.]? is \.? and your first regex can be changed to /\w*/. Commented Jun 25, 2014 at 8:31
  • Possible duplication? Find multiple patterns with a single preg_match_all in PHP Commented Jun 25, 2014 at 8:32
  • 1
    Could you tell us what are you trying to match (not how)? Commented Jun 25, 2014 at 8:37

2 Answers 2

4
  • Your patterns probably don't work all that well (they look cobbled together)
  • That being said, the way to say OR in regex is the alternation operator |
  • Therefore you could join them with $regex = "~\S+[\.]?\s?\S*|((\w+)?)~";

... but in my view this pattern needs a beauty job. :)

  1. \S+[\.]?\s?\S* can be tidied up as \S+\.?\s?\S*, but the \S+ will eat up the \. so you probably need a lazy quantifier: \S+?\.?\s?\S*... But this is just some solid chars + an optional dot + one optional space + optional solid chars... So the period in the middle can go, as \S already specified it. We end up with \S+\s?\S*
  2. ((\w+)?) is just \w*, unless you need a capture group.
  3. But \S+\s?\S* is able to match everything \w* matches, except for the empty string, so you can reduce this to \S+\s?\S*

Finally

Therefore, you would end up with something like:

$regex = "~\S+\s?\S*~";
$count = preg_match_all($regex,$string,$matches);

If you do want this to also be able to match the empty string, as ((\w+)?) did, then make the whole thing optional:

$regex = "~(?:\S+\s?\S*)?~";
Sign up to request clarification or add additional context in comments.

Comments

0

Just combine the regexes like below using an logical OR(|) operator,

$regex = "~/(?:((\w+)?)|\S+[\.]?\s?\S*)/~"

(?:) represents a non-capturing group.

It would print the strings which are matched by first or second regex.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.