php在字符串中找到多个字符串

时间:2016-12-23 08:44:25

标签: php substr

我有一个基本上在描述中检索产品ID的函数。

private function scanForProductIdInDescription($string, $start, $end) {
        $startpos = strpos($string, $start) + strlen($start);
        if (strpos($string, $start) !== false) {
            $endpos = strpos($string, $end, $startpos);
            if (strpos($string, $end, $startpos) !== false) {
                return substr($string, $startpos, $endpos - $startpos);
            }
        }
    }

我按如下方式使用它:

$from = "{PID =";
 $end = "}";
$description = 'some text {PID =340}  {PID =357}';
 $product_id = $this->scanForProductIdInDescription($description, $from, $end);

此刻,它只会在字符串中首次出现。我需要找到字符串中的所有出现。结果应该是: $ product_id = 340,357;

感谢

5 个答案:

答案 0 :(得分:3)

使用正则表达式代替strpos()将是您最好的选择。我很快将以下内容放在一起,这与你的例子有关;

\{PID\s=([0-9]*)\}

You can see a working version here

在PHP中使用它看起来像;

$re = '/\{PID\s=([0-9]*)\}/';
$str = 'some text {PID =340}  {PID =357}';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

编辑:编辑仅返回匹配字符串中的实际ID。 IMO - 这是一个比其他2个答案更好的解决方案,因为它返回任意长度的ID,并且只返回以您提供的格式匹配的ID。

我还更新了我的工作示例。

答案 1 :(得分:1)

您可以使用preg_match_all:

$description = 'some text {PID =340}  {PID =357}';

preg_match_all('/=([0-9]+)\}/', $description, $matches);

var_dump($matches);

结果是:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "=340}"
    [1]=>
    string(5) "=357}"
  }
  [1]=>
  array(2) {
    [0]=>
    string(3) "340"
    [1]=>
    string(3) "357"
  }
}

答案 2 :(得分:1)

您可以使用preg_match_all,如下所示:

<?php 


    // $sPattern = '^{PID\s=\d{3}}^';

    // by using a capture group "(" + ")" to enclose the number (\d), you can output just the numbers
    $sPattern = '{PID\s=(\d{3})}';

    $aOutput = array();
    $sString = 'some text {PID =340}  {PID =357}';

    preg_match_all($sPattern, $sString, $aOutput);

    // implode the first capture group to a string
    $aOutput = implode(",", $aOutput[1]);

    echo "<pre>";
    var_dump($aOutput);
?>

这将输出:

string(7) "340,357"

答案 3 :(得分:1)

要获得所需的结果( PID 数字) - 请使用以下方法:

$description = 'some text {PID =340}  {PID =357}';
preg_match_all("/(?<=\{PID =)\d+(?=\})/", $description, $matches);
$result = $matches[0];

print_r($result);

输出:

Array
(
    [0] => 340
    [1] => 357
)

答案 4 :(得分:1)

通过使用\K在所需的数字子字符串之前重新启动完整字符串匹配,可以完全避免捕获组。

代码:(演示:https://3v4l.org/WalUc

$description = 'some text {PID =340}  {PID =357}';
echo implode(',', preg_match_all('~\{PID =\K\d+~', $description, $out) ? $out[0] : []);

输出:

340,357

此技术的好处是:

  1. 使正则表达式引擎执行的步骤更少。
  2. matches数组($out)中没有不必要的膨胀。
相关问题