3

我有一个看起来有点像这样的字符串

1: u:mads g:folk 2: g:andre u:jens u:joren

我需要的是一种方法(我猜是正则表达式)来获取例如 u:jens 和它之后的数字(1 或 2)。

我如何在 php 中解决这个问题(最好只有一个函数)?

4

3 回答 3

2

这将找到所有匹配项。如果您只需要第一个,请preg_match改用。

<?php
$subject = '1: u:mads g:folk 2: g:andre u:jens u:joren 3: u:jens';
preg_match_all('#(\d+):[^\d]*?u:jens#msi', $subject, $matches);
foreach ($matches[1] as $match) {
    var_dump($match);
}
?>
于 2013-01-25T12:25:29.340 回答
0

您可以使用以下正则表达式:

(\d+):(?!.*\d+:.*).*u:jens

您要查找的数字放在第一个捕获组中。因此,如果您使用的是 PHP:

$matches = array();
$search = '1: u:mads g:folk 2: g:andre u:jens u:joren';
if (preg_match('/(\d+):(?!.*\d+:.*).*u:jens/', $search, $matches)) {
  echo 'Found at '.$matches[1]; // Will output "Found at 2"
}
于 2013-01-25T12:25:00.150 回答
0

这将解析字符串并返回一个数组,其中包含找到搜索字符串的数字键:

function whereKey($search, $key) {
  $output = array();
  preg_match_all('/\d+:[^\d]+/', $search, $matches);

  if ($matches[0]) {
    foreach ($matches[0] as $k) {
      if (strpos($k, $key) !== FALSE) {
        $output[] = (int) current(split(':', $k));
      }
    }
  }

  return $output;
}

例如:

whereKey('1: u:mads g:folk 2: g:andre u:jens u:joren', 'u:jens')

...将返回:

array(1) { [0]=> int(2) }
于 2013-01-25T13:10:06.813 回答