PHP - 如何找到字符串中除预先指定字符之外的任何字符第一次出现的位置


PHP - How do I find the position of the first occurrence of ANY CHARACTER BUT a pre-specified character in a string?

我有一个可变长度的字符串。每个字符都是"r"、"w"或"x"。

我知道如何使用 strpos() 来查找字符串中第一次出现的字符的位置。但我想找到第一次出现的"r"或"w"的位置。换句话说,我想找到第一次出现的"不是x"的位置。

例如:

"rwxrxx" would return 0
"wxrr" would return 0
"xxwwwwwr" would return 2
"xxrx" would return 2
"xxxwrrwxxrrwxrrwwxrxrw" would return 3

执行此操作的最佳方法(尽管有一个小警告)是 strspn() 或 strcspn() 之一,但根据您想要执行的操作,略有不同...

如果要查找"x"以外的字符的第一个匹配项,则需要strspn()

php > $pos = strspn('xxxwrrw', 'x');
php > var_dump($pos);
int(3)

如果你需要第一次出现特定的"w"或"r",你需要strcspn()

php > $pos = strcspn('xxxwrrw', 'rw');
php > var_dump($pos);
int(3)

但正如我所说,有一个小警告...这些函数返回与给定掩模/针匹配或不匹配的初始长度strcspn()中的"C"代表"计数器")。
这意味着他们永远不会返回false并且您总是会得到一个积极的结果,例如"xxxxxxx":

php > $pos = strcspn('xxxxxx', 'rw');
php > var_dump($pos);
int(6)

因此,您可能需要检查返回的位置是否确实存在,如下所示:

php > $input = 'xxxxxx';
php > $pos   = strspn($input, 'x'); // i.e. $pos = 6;
php > var_dump(isset($input[$pos]));
bool(false) // There was no character other than 'x'

原答案:

php >     $string = 'xrwxrxx';
php >     preg_match('/[^x]/', $string, $matches, PREG_OFFSET_CAPTURE);
php >     echo $matches[0][1];
1