php - Is there a way to move/reset the search pointer in preg_match_all()? -
take following example,
preg_match_all("/(^|-)[a-z]+(-|$)/i", "foo-bar-moo", $matches);
this (correctly) returns following matches,
foo- -moo
however, need generate following matches output,
foo- -bar- -moo
is there way this? example moving search pointer 1 character after match?
my other idea put in while()
loop, removing matches on each loop, until matches found.
thanks.
edit: tried simplify issue make question clearer, in doing seem have misrepresented issue was. apologies.
basically needed way match word in string character preceding or character following character, @ same time without capturing these leading , trailing characters in match.
i under impression couldn't this, instead decided capture leading/trailing characters , remove them myself. led me issue above.
as tim pietzcker pointed out, needed lookarounds.
so example above, solution follows,
preg_match_all('/(?<=^|-)[a-z]+(?=-|$)/', "foo-bar-moo", $result);
and outputs,
foo bar moo
thanks again answers , help.
use lookaround , put capturing groups in lookaround expressions. allows in single preg_match_all()
call , still capture -
es if present:
preg_match_all('/(?<=(^|-))([a-z]+)(?=(-|$))/', $subject, $result, preg_set_order); ($match = 0; $match < count($result); $match++) { echo $result[$match][1] . $result[$match][2] . $result[$match][3]; }
Comments
Post a Comment