关于strpos的问题。如何获得第二次出现的字符串?

时间:2020-12-28 13:12:29

I understand that this function will get the first occurrence of the string.

据我所知,这个函数将首次出现字符串。

But what I want is the 2nd occurrence.

但我想要的是第二次出现。

How to go about doing that?

怎么去那样做?

10 个解决方案

#1


43  

You need to specify the offset for the start of the search as the optional third parameter and calculate it by starting the search directly after the first occurrence by adding the length of what you're searching for to the location you found it at.

您需要将搜索开始的偏移量指定为可选的第三个参数,并通过在第一次出现后直接开始搜索来计算它,方法是将您搜索的内容的长度添加到您找到的位置。

$pos1 = strpos($haystack, $needle);
$pos2 = strpos($haystack, $needle, $pos1 + strlen($needle));

#2


41  

I know this question is kind of old, but here's a function I wrote to get the Xth occurrence of a substring, which may be helpful for other people that have this issue and stumble over this thread.

我知道这个问题有点陈旧,但这是我写的一个函数,用于获取子串的第X次出现,这可能对其他有此问题且偶然发现此线程的人有所帮助。

/**
 * Find the position of the Xth occurrence of a substring in a string
 * @param $haystack
 * @param $needle
 * @param $number integer > 0
 * @return int
 */
function strposX($haystack, $needle, $number){
    if($number == '1'){
        return strpos($haystack, $needle);
    }elseif($number > '1'){
        return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
    }else{
        return error_log('Error: Value for parameter $number is out of range');
    }
}

#3


8  

The recursive function from Smokey_Bud was slowing my script drastically down. Using a regular expression is much faster in this case (for finding any occurence):

Smokey_Bud的递归函数大大减慢了我的脚本速度。在这种情况下使用正则表达式要快得多(用于查找任何出现):

function strposX($haystack, $needle, $number)
{
    // decode utf8 because of this behaviour: https://bugs.php.net/bug.php?id=37391
    preg_match_all("/$needle/", utf8_decode($haystack), $matches, PREG_OFFSET_CAPTURE);
    return $matches[0][$number-1][1];
}

// get position of second 'wide'
$pos = strposX('Hello wide wide world', 'wide', 2);

#4


6  

You can try this, though I haven't tested it out-

你可以试试这个,虽然我还没有测试过 -

$pos = strpos($haystack, $needle, strpos($haystack, $needle)+strlen($needle));

#5


6  

an alternate way should be explode the string by desired character and then get it from array on desired index

另一种方法应该是通过所需的字符爆炸字符串,然后从所需索引的数组中获取它

for example I have a string like

例如我有一个字符串

$str = "hello-world-how-are-you-doing";

And I need to get text after 4th occurrence of "-" i.e I want "you"

我需要在第四次出现“ - ”之后得到文本,即我想要“你”

I need to explode it to make it an array

我需要将它爆炸以使其成为一个数组

$array = explode("-", $str);
echo $array[4];

#6


2  

Simple is beautiful

简单即美

function strposX($haystack, $needle, $n = 0)
{
    $offset = 0;

    for ($i = 0; $i < $n; $i++) {
        $pos = strpos($haystack, $needle, $offset);

        if ($pos !== false) {
            $offset = $pos + strlen($needle);
        } else {
            return false;
        }
    }

    return $offset;
}

$offset = strposX($result, "\n", $n);

if ($offset === false) {
    $offset = strlen($result) - 1;
}

#7


0  

just worked for me to find if are 2 or more occurrence of a char, then by strlen them i found that exist 2 occurrence ex ( i dont use $matches at all):

只是为我工作,找到是否有2个或更多的char出现,然后通过strlen他们发现存在2个事件ex(我根本不使用$ matches):

$string = '1234|6|#red';

if(strlen(preg_match_all('/|/', $string,$matches, PREG_OFFSET_CAPTURE)) ==2){

echo 'i have 2 occurence of char: |';

    }

#8


0  

Old question, but if someone's looking for a way to find occurrences from the END of the string (for example 3rd occurrence of dot from the end) the following function works (didn't want to use oncodes function not to mess with encoding)

老问题,但是如果有人正在寻找从字符串的END中查找事件的方法(例如,从结尾第3次出现点),则以下函数可以正常工作(不想使用oncodes函数而不是乱码编码)

$str = "NooooYesYesNo";

function find_occurence_from_end($haystack, $needle, $num) {

    for ($i=1; $i <=$num ; $i++) {

        # first loop return position of needle
        if($i == 1) {
            $pos = strrpos($haystack, $needle);
        }

        # subsequent loops trim haystack to pos and return needle's new position
        if($i != 1) {

            $haystack = substr($haystack, 0, $pos);
            $pos = strrpos($haystack, $needle);

        }

    }

    return $pos;

}

$pos = find_occurence_from_end($str, "Yes", 2);

// 5

It's super simple. Basically each time it finds an occurrence of your needle it "trims" the string to that position. So it keeps on trimming it while returning the latest position each time.

这非常简单。基本上每当它发现你的针头出现时,它会将弦“修剪”到那个位置。所以它一直在修剪它,同时每次都返回最新的位置。

#9


-1  

Please check the following code ... it works pretty fine for me.

请检查以下代码......它对我来说非常好。

<?php
    function f_srch ($s1, $par) {
        echo 'Searching for [' . $par . '] in [' . $s1 . ']<br>';
        $k = 0; //while loop
        $i = 0; // counter

        while ($k >= 0) {
            $pos = strpos($s1, $par, $k);
            if ($pos === false) {
                $k=-1;
                echo 'Letter not found'.'<br>';
            } else {
                if ($pos == $k) { 
                    echo 'The position of the letter is '.$pos.'<br>'; 
                    $i++;
                }
                $k++;
            } 
        }
        echo 'The letter was found ' . $i . ' time(s).'.'<br>'; 
    }
    f_srch('i am searching for a letter in this sentence','t');
?>

#10


-14  

http://php.net/strpos

http://php.net/strpos

$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1);  // $pos = 7, not 0

#1


43  

You need to specify the offset for the start of the search as the optional third parameter and calculate it by starting the search directly after the first occurrence by adding the length of what you're searching for to the location you found it at.

您需要将搜索开始的偏移量指定为可选的第三个参数,并通过在第一次出现后直接开始搜索来计算它,方法是将您搜索的内容的长度添加到您找到的位置。

$pos1 = strpos($haystack, $needle);
$pos2 = strpos($haystack, $needle, $pos1 + strlen($needle));

#2


41  

I know this question is kind of old, but here's a function I wrote to get the Xth occurrence of a substring, which may be helpful for other people that have this issue and stumble over this thread.

我知道这个问题有点陈旧,但这是我写的一个函数,用于获取子串的第X次出现,这可能对其他有此问题且偶然发现此线程的人有所帮助。

/**
 * Find the position of the Xth occurrence of a substring in a string
 * @param $haystack
 * @param $needle
 * @param $number integer > 0
 * @return int
 */
function strposX($haystack, $needle, $number){
    if($number == '1'){
        return strpos($haystack, $needle);
    }elseif($number > '1'){
        return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
    }else{
        return error_log('Error: Value for parameter $number is out of range');
    }
}

#3


8  

The recursive function from Smokey_Bud was slowing my script drastically down. Using a regular expression is much faster in this case (for finding any occurence):

Smokey_Bud的递归函数大大减慢了我的脚本速度。在这种情况下使用正则表达式要快得多(用于查找任何出现):

function strposX($haystack, $needle, $number)
{
    // decode utf8 because of this behaviour: https://bugs.php.net/bug.php?id=37391
    preg_match_all("/$needle/", utf8_decode($haystack), $matches, PREG_OFFSET_CAPTURE);
    return $matches[0][$number-1][1];
}

// get position of second 'wide'
$pos = strposX('Hello wide wide world', 'wide', 2);

#4


6  

You can try this, though I haven't tested it out-

你可以试试这个,虽然我还没有测试过 -

$pos = strpos($haystack, $needle, strpos($haystack, $needle)+strlen($needle));

#5


6  

an alternate way should be explode the string by desired character and then get it from array on desired index

另一种方法应该是通过所需的字符爆炸字符串,然后从所需索引的数组中获取它

for example I have a string like

例如我有一个字符串

$str = "hello-world-how-are-you-doing";

And I need to get text after 4th occurrence of "-" i.e I want "you"

我需要在第四次出现“ - ”之后得到文本,即我想要“你”

I need to explode it to make it an array

我需要将它爆炸以使其成为一个数组

$array = explode("-", $str);
echo $array[4];

#6


2  

Simple is beautiful

简单即美

function strposX($haystack, $needle, $n = 0)
{
    $offset = 0;

    for ($i = 0; $i < $n; $i++) {
        $pos = strpos($haystack, $needle, $offset);

        if ($pos !== false) {
            $offset = $pos + strlen($needle);
        } else {
            return false;
        }
    }

    return $offset;
}

$offset = strposX($result, "\n", $n);

if ($offset === false) {
    $offset = strlen($result) - 1;
}

#7


0  

just worked for me to find if are 2 or more occurrence of a char, then by strlen them i found that exist 2 occurrence ex ( i dont use $matches at all):

只是为我工作,找到是否有2个或更多的char出现,然后通过strlen他们发现存在2个事件ex(我根本不使用$ matches):

$string = '1234|6|#red';

if(strlen(preg_match_all('/|/', $string,$matches, PREG_OFFSET_CAPTURE)) ==2){

echo 'i have 2 occurence of char: |';

    }

#8


0  

Old question, but if someone's looking for a way to find occurrences from the END of the string (for example 3rd occurrence of dot from the end) the following function works (didn't want to use oncodes function not to mess with encoding)

老问题,但是如果有人正在寻找从字符串的END中查找事件的方法(例如,从结尾第3次出现点),则以下函数可以正常工作(不想使用oncodes函数而不是乱码编码)

$str = "NooooYesYesNo";

function find_occurence_from_end($haystack, $needle, $num) {

    for ($i=1; $i <=$num ; $i++) {

        # first loop return position of needle
        if($i == 1) {
            $pos = strrpos($haystack, $needle);
        }

        # subsequent loops trim haystack to pos and return needle's new position
        if($i != 1) {

            $haystack = substr($haystack, 0, $pos);
            $pos = strrpos($haystack, $needle);

        }

    }

    return $pos;

}

$pos = find_occurence_from_end($str, "Yes", 2);

// 5

It's super simple. Basically each time it finds an occurrence of your needle it "trims" the string to that position. So it keeps on trimming it while returning the latest position each time.

这非常简单。基本上每当它发现你的针头出现时,它会将弦“修剪”到那个位置。所以它一直在修剪它,同时每次都返回最新的位置。

#9


-1  

Please check the following code ... it works pretty fine for me.

请检查以下代码......它对我来说非常好。

<?php
    function f_srch ($s1, $par) {
        echo 'Searching for [' . $par . '] in [' . $s1 . ']<br>';
        $k = 0; //while loop
        $i = 0; // counter

        while ($k >= 0) {
            $pos = strpos($s1, $par, $k);
            if ($pos === false) {
                $k=-1;
                echo 'Letter not found'.'<br>';
            } else {
                if ($pos == $k) { 
                    echo 'The position of the letter is '.$pos.'<br>'; 
                    $i++;
                }
                $k++;
            } 
        }
        echo 'The letter was found ' . $i . ' time(s).'.'<br>'; 
    }
    f_srch('i am searching for a letter in this sentence','t');
?>

#10


-14  

http://php.net/strpos

http://php.net/strpos

$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1);  // $pos = 7, not 0