regex 如何在字符串“constant-string-NUMBER-*"中得到数字?

0yg35tkg  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(93)

我有像constant-string-NUMBER-*这样的字符串

  • constant-string-是常量字符串(我知道它,并且可以在获取数字时使用它),例如fix-str-
  • NUMBER是任意自然数
  • -*可以是任何字符串

字符串结果示例:

fix-str-0
// result: 0

fix-str-0-another-str
// result: 0

fix-str-123
// result: 123

fix-str-456789
// result: 456789

fix-str-123456789-yet-another-str
// result: 1234567899

fix-str-999999-another-str-123
// result: 999999

我想在PHP中从这些字符串中提取数字,以便将此数字与变量(例如$numberFromString = ?)关联。
有什么见解吗?

ukqbszuj

ukqbszuj1#

试试这个:

fix-str-(\d+)
  • fix-str-匹配此字符串。
  • (\d+)后跟一个或多个数字,并将该数字保存在第一个捕获组中。
    • 编辑**

在@user3783243中,我们还可以使用fix-str-\K\d+,而不需要捕获组。

fix-str-\K\d+
  • fix-str-匹配此字符串,则..
  • \K重置所报告匹配的起始点。
  • \d+然后匹配一个或多个数字。

参见regex demo

<?php 
$str ="fix-str-123456789-yet-another-str fix-str-234";

$pattern = "/fix-str-\K\d+/";

preg_match($pattern, $str, $arr1); //Find only the first match.

echo "The first match: " . $arr1[0]; //Output: 123456789

echo "\n\n\n";

preg_match_all($pattern, $str, $arr2); //Find all the matches.

echo "All the matches: " . implode(',', $arr2[0]); //Output: 123456789,234
?>
hs1ihplo

hs1ihplo2#

基于你的字符串例子,有两种可能的方法,一种方法可以使用explode,当然另一种方法可以使用preg_match作为regex,我将展示这两种方法,只是为了说明regex并不总是绝对必要的。
使用explode

$strings = [
'fix-str-0',
'fix-str-0-another-str',
'fix-str-123',
'fix-str-456789',
'fix-str-123456789-yet-another-str',
'fix-str-999999-another-str-123',
];

$match = [];
$matches = [];
foreach ($strings as $string) {
    $match = explode('-', $string);
    
    if (count($match) >= 3) {
        $matches[] = $match[2]; // Array offset 2 has the number
    }
}

foreach($matches as $found) {
    echo $found, PHP_EOL;
}

// Output:

0
0
123
456789
123456789
999999

使用preg_match

$strings = [
'fix-str-0',
'fix-str-0-another-str',
'fix-str-123',
'fix-str-456789',
'fix-str-123456789-yet-another-str',
'fix-str-999999-another-str-123',
];

$match = [];
$matches = [];
foreach ($strings as $string) {
      // match 1 or more digits, store to $match
    preg_match('/(\d+)/', $string, $match);
    
    if (!empty($match)) {
        $matches[] = $match[0]; // use the first match
    }
}

foreach($matches as $found) {
    echo $found, PHP_EOL;
}

// Output:

0
0
123
456789
123456789
999999
6yt4nkrj

6yt4nkrj3#

你可以将一个字符串表示为一个字符数组,使用PHP的substr()函数,其中第二个参数是字符串从哪个数字开始。
示例。从字符串返回“world”:

<?php
echo substr("Hello world",6);
?>

信息来自这里:https://www.w3schools.com/php/func_string_substr.asp

相关问题