I'm trying to find the position of any of a number of characters, but need to be able to set a search offset.
This is precisely the functionality of strpos()
but matching any of a number of characters rather than a single string/character. If strpos()
would accept an array of $needles it would be exactly what I need (assuming it returns the position of the earliest match in $haystack).
strpbrk()
has exactly what's needed in terms of matching a set of characters, but this does not allow an offset so that I can move along the string after each successful match.
This seems an odd thing to be missing from the PHP string functions, is there something I am missing?
Here is a code summary:
while($pos=strpos($el->text(), '*_-!`' ,$el->position())!==FALSE){ $el->position($pos); foreach ($HandlerTypes as $Type){ // Note: $el->position is modified within this function $this->markSpan($Type, $el); } }
Where I'm looking for any of *
, _
, -
, !
or ` rather than the string of them. Any marker might appear more than once in the string.
thanks.
Regular expressions to the rescue!
$s = 'skipbfoobarxarjar';
preg_match_all('~[bxj]~', $s, $m, PREG_OFFSET_CAPTURE, 5);
print_r($m[0]);
Result:
[0] => Array
(
[0] => b
[1] => 8
)
[1] => Array
(
[0] => x
[1] => 11
)
[2] => Array
(
[0] => j
[1] => 14
)