PHP 查找字符串中所有出现的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15737408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:51:58  来源:igfitidea点击:

PHP Find all occurrences of a substring in a string

phpstring

提问by muncherelli

I need to parse an HTML document and to find all occurrences of string asdfin it.

我需要解析一个 HTML 文档并在其中找到所有出现的字符串asdf

I currently have the HTML loaded into a string variable. I would just like the character position so I can loop through the list to return some data after the string.

我目前已将 HTML 加载到字符串变量中。我只想要字符位置,这样我就可以遍历列表以在字符串后返回一些数据。

The strposfunction only returns the firstoccurrence. How about returning allof them?

strpos函数只返回第一次出现。全部归还怎么样?

回答by Adam Plocher

Without using regex, something like this should work for returning the string positions:

不使用正则表达式,这样的事情应该可以用于返回字符串位置:

$html = "dddasdfdddasdffff";
$needle = "asdf";
$lastPos = 0;
$positions = array();

while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
    $positions[] = $lastPos;
    $lastPos = $lastPos + strlen($needle);
}

// Displays 3 and 10
foreach ($positions as $value) {
    echo $value ."<br />";
}

回答by Salman A

You can call the strposfunction repeatedly until a match is not found. You must specify the offset parameter.

您可以strpos重复调用该函数,直到找不到匹配项。您必须指定偏移参数。

Note: in the following example, the search continues from the nextcharacter instead of from the end of previous match. According to this function, aaaacontains threeoccurrences of the substring aa, not two.

注意:在以下示例中,搜索从下一个字符开始,而不是从前一个匹配的结尾开始。根据这个函数,aaaa包含三个出现的子字符串aa,而不是两个。

function strpos_all($haystack, $needle) {
    $offset = 0;
    $allpos = array();
    while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
        $offset   = $pos + 1;
        $allpos[] = $pos;
    }
    return $allpos;
}
print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));

Output:

输出:

Array
(
    [0] => 0
    [1] => 1
    [2] => 8
    [3] => 9
    [4] => 16
    [5] => 17
)

回答by Nirmal Ram

Its better to use substr_count. Check out on php.net

它更好地使用substr_count。在php.net上查看

回答by Ryodo

function getocurence($chaine,$rechercher)
        {
            $lastPos = 0;
            $positions = array();
            while (($lastPos = strpos($chaine, $rechercher, $lastPos))!== false)
            {
                $positions[] = $lastPos;
                $lastPos = $lastPos + strlen($rechercher);
            }
            return $positions;
        }

回答by Kach

This can be done using strpos()function. The following code is implemented using for loop. This code is quite simple and pretty straight forward.

这可以使用strpos()函数来完成。以下代码使用 for 循环实现。这段代码非常简单而且非常直接。

<?php

$str_test = "Hello World! welcome to php";

$count = 0;
$find = "o";
$positions = array();
for($i = 0; $i<strlen($str_test); $i++)
{
     $pos = strpos($str_test, $find, $count);
     if($pos == $count){
           $positions[] = $pos;
     }
     $count++;
}
foreach ($positions as $value) {
    echo '<br/>' .  $value . "<br />";
}

?>

回答by Deepu

Use preg_match_allto find alloccurrences.

使用preg_match_all找到的所有事件。

preg_match_all('/($[a-z]+)/i', $str, $matches);

For further reference check this link.

如需进一步参考,请查看此链接

回答by Jalo

Simple strpos_all()function.

简单的strpos_all()函数。

function strpos_all($haystack, $needle_regex)
{
    preg_match_all('/' . $needle_regex . '/', $haystack, $matches, PREG_OFFSET_CAPTURE);
    return array_map(function ($v) {
        return $v[1];
    }, $matches[0]);
}

Usage: Simple string as needle.

用法:简单的线作为针。

$html = "dddasdfdddasdffff";
$needle = "asdf";

$all_positions = strpos_all($html, $needle);
var_dump($all_positions);

Output:

输出:

array(2) {
  [0]=>
  int(3)
  [1]=>
  int(10)
}

Or with regex as needle.

或者用正则表达式作为针。

$html = "dddasdfdddasdffff";
$needle = "[d]{3}";

$all_positions = strpos_all($html, $needle);
var_dump($all_positions);

Output:

输出:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(7)
}

回答by mangrove

Salman A has a good answer, but remember to make your code multibyte-safe. To get correct positions with UTF-8, use mb_strpos instead of strpos:

Salman A 有一个很好的答案,但请记住使您的代码多字节安全。要使用 UTF-8 获得正确的位置,请使用 mb_strpos 而不是 strpos:

function strpos_all($haystack, $needle) {
    $offset = 0;
    $allpos = array();
    while (($pos = mb_strpos($haystack, $needle, $offset)) !== FALSE) {
        $offset   = $pos + 1;
        $allpos[] = $pos;
    }
    return $allpos;
}
print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));