如何在PHP中找到字符串中数字的位置


How to find the place of digits in a string in PHP

我想找到一个基于数字的子字符串在字符串中的位置

$str = " test No. 82 and No. 8 more No. 234";
$needle = "No. 8";

I tried strpos as

$index = stripos($str,$needle);

,但它发现No. 82而不是No. 8

最简单的方法是使用preg_matchPREG_OFFSET_CAPTURE ?真的需要regex吗?

"Regex"方法更适合这种复杂的情况,preg_match_all函数将完成这项工作:

$str = " test No. 82 and No. 8 more No. 234";
preg_match_all("/No'.'s+'d+'b/", $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches[0]);

根据您的附加条件搜索$needle:
-我们应该通过使用元字符'b

来考虑搜索"针"的正确边界
$str = " test No. 82 and No. 8 more No. 234";
$needle = "No. 8";
preg_match_all("/$needle'b/", $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches[0]);
输出:

Array
(
    [0] => Array
        (
            [0] => No. 8
            [1] => 17
        )
)

您需要一个正则表达式来匹配精确的序列模式。我建议这样做:

<?php
$subject = " test No. 82 and No. 8 more No. 234";
$pattern = '/No'. 'd+/';
$offset = 0;
while (preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, $offset+1)) {
    $offset = $matches[0][1];
    var_dump($matches);
}

输出,当然可以进一步处理,是:

array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(6) "No. 82"
    [1] =>
    int(6)
  }
}
array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(5) "No. 8"
    [1] =>
    int(17)
  }
}
array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(7) "No. 234"
    [1] =>
    int(28)
  }
}

根据您的确切需求,您可能希望将模式修改为'/No'. ('d+)/'以精确匹配数字部分。显然,您还必须将偏移线调整为$offset = $matches[1][1];