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
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
OR
in regex is the alternation operator |
$regex = "~\S+[\.]?\s?\S*|((\w+)?)~";
... but in my view this pattern needs a beauty job. :)
\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*
((\w+)?)
is just \w*
, unless you need a capture group.\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*)?~";
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.