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

  • 1
    What's wrong with [alternation](http://www.regular-expressions.info/alternation.html)? BTW, `[\.]?` is `\.?` and your first regex can be changed to `/\w*/`. – Robin Jun 25 '14 at 08:31
  • Possible duplication? [Find multiple patterns with a single preg_match_all in PHP](http://stackoverflow.com/questions/4536014/find-multiple-patterns-with-a-single-preg-match-all-in-php) – pes502 Jun 25 '14 at 08:32
  • 1
    Could you tell us _what_ are you trying to match (not _how_)? – georg Jun 25 '14 at 08:37

2 Answers2

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*)?~";
zx81
  • 41,100
  • 9
  • 89
  • 105
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.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274