php - Best way to find matches of several substrings in string? -
i have $a=array('1str','2str','3str')
, $str ='123 2str 3str 1str'
, trying simple thing - find position of each item of $a
in $str.
it's easy done loops , strpos
, i'm curious best (and short, actually) way positions?
actually need nearest of found items in string (2str)
if need offsets, use preg_match_all function , flag preg_offset_capture
if(preg_match_all('/'.implode('|', $a).'/', $str, $out, preg_offset_capture)) print_r($out[0]);
useful if need match such \b
word boundaries or caseless matching using i
flag.
as @mike.k commented: if $a
contains characters special meaning inside regex pattern, need escape first: array_map(function ($v) { return preg_quote($v, "/"); }, $a)
to 1 that's closest start, don't need offsets. preg_match
, simple pattern 1str|2str|3str
(see test @ eval.in).
if(preg_match('/'.implode('|', $a).'/', $str, $out, preg_offset_capture)) echo "the substring that's closest start \"".$out[0][0]."\" @ offset ".$out[0][1];
the substring that's closest start "2str" @ offset 4
if don't need offset/regex @ all, idea first match: sorting usort pos
usort($a, function ($x, $y) use (&$str) { return (strpos($str, $x) < strpos($str, $y)) ? -1 : 1; });
echo $a[0]; > 2str
(anonymous functions usort require @ least php 5.3)
Comments
Post a Comment