在字符串中查找多个子字符串匹配的最佳方法?

el *_*ude 2 php string search strpos

我有$a=array('1str','2str','3str')$str ='123 2str 3str 1str'
尝试做一件简单的事情 - 找到$a$ str 中每个项目的位置.

使用循环很容易strpos,但我很好奇获得这些职位的最佳方式(实际上是短期的)是什么?

实际上我需要在字符串中找到最近的项目(2str)

mik*_*e.k 5

你可以这样做 array_map()

$a = array('1str', '2str', '3str');
$str ='123 2str 3str 1str';

function my_strpos($needle) {
    global $str;
    return strpos($str, $needle);
}

$positions = array_map('my_strpos', $a);
Run Code Online (Sandbox Code Playgroud)

print_r($positions); 得到:

Array
(
    [0] => 14
    [1] => 4
    [2] => 9
)
Run Code Online (Sandbox Code Playgroud)