【问题标题】:How to get starting positions of all substring occurences in PHP?如何获取 PHP 中所有子字符串出现的起始位置?
【发布时间】:2014-03-19 01:40:12
【问题描述】:

是否有现成的函数来获取位置数组,某个子字符串从哪里开始?

例如,

$needle = "apple";
$haystack = "one apple two apples three apples";
$r = f($haystack , $needle);
// should give: 
$r = array(4 , 13 , 24);
// i.e. the positions of "a" letters

我知道 substr_count 给出了子字符串的数量,但是我怎样才能得到起始位置呢?

感谢您的帮助!

【问题讨论】:

    标签: php arrays substr substring


    【解决方案1】:
    $needle = "apple";
    $haystack = "one apple two apples three apples";
    $count = preg_match_all(
        '/'.preg_quote($needle).'/', 
        $haystack, $matches, 
        PREG_OFFSET_CAPTURE
    );
    if ($count) {
        var_dump($matches[0]);
    }
    

    如果您有 PHP 5.5+,您可以使用数组列轻松获取 $matches 中的所有偏移量

    var_dump(array_column($matches[0], 1));
    

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 2016-03-06
      • 2012-09-14
      • 2021-03-30
      • 2011-05-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多