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

时间:2010-06-27 03:45:19

标签: php string search

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

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

如何去做?

14 个答案:

答案 0 :(得分:47)

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

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

答案 1 :(得分:46)

我知道这个问题有点陈旧,但这是我写的一个函数,用于获取子字符串的第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');
    }
}

答案 2 :(得分:10)

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

ë

答案 3 :(得分:9)

要找到第二次出现的字符串,您可以使用strpos和“offset”参数,方法是将前一个偏移量添加到strpos。

$source = "Hello world, how you doing world...world ?";
$find = "world";
$offset = 0;
$findLength = strlen($find);
$occurrence = 0;

while (($offset = strpos($source, $find, $offset))!== false) {
    if ($occurrence ++) {
      break;
    }
    $offset += $findLength; 
}

echo $offset;

您可以通过将偏移存储到数组

来查找所有实例
while (($offset = strpos($source, $find, $offset))!== false) {
  $occurrences[] = $offset;
  $offset += $findLength; 
}
var_export($occurrences);

或者可以通过匹配$ occurrence

来获得特定事件
//find 3rd occurrence
if ($occurrence ++ == 2) {
    break;
}

答案 4 :(得分:7)

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

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

答案 5 :(得分:3)

简单就是美丽

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;
}

答案 6 :(得分:0)

刚刚为我工作,发现是否有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: |';

    }

答案 7 :(得分:0)

老问题,但是如果某人正在寻找从字符串的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

这非常简单。基本上每当它发现你的针头出现时它会修剪&#34;该位置的字符串。因此,每次返回最新位置时,它都会继续修剪它。

答案 8 :(得分:0)

古老的问题,但是如何使用explode

$corpus = 'how many words are there in a dictionary? I'm not going to count them word by word...' 
$looking_for = 'word';
$instance = 2;

$t = explode($looking_for, $corpus, $instance + 1);
array_pop($t);
$position = strlen(implode($looking_for, $t));

答案 9 :(得分:0)

function substr_Index( $str, $nth ){
    $str2 = '';
    $posTotal = 0;
    for($i=0; $i < $nth; $i++){

        if($str2 != ''){
            $str = $str2;
        }

        $pos   = strpos($str, ':');
        $str2  = substr($str, $pos+1);
        $posTotal += $pos+1;

    }
    return $posTotal-1;
}


echo substr($mystring, substr_Index( $mystring , 2) );

函数返回第n个定界符的位置。

substr_Index的第二个参数必须大于0;

要查找第二次使用,请使用substr_Index( $mystring , 2)

答案 10 :(得分:0)

轻松地做到这一点:

$i = $pos = 0;    
do {
        $pos = strpos( $string, $needle, $pos+1 );
} while( $i++ < $nth);

根据您的情况,$ nth等于2。

答案 11 :(得分:0)

case let x where x > 0 && x <= f1:

答案 12 :(得分:-1)

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

<?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');
?>

答案 13 :(得分:-15)

http://php.net/strpos

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