PHP 从字符串中获取数字


php get the number from a string

我有这个字符串

@[123:Peterwateber] 你好,095032sdfsdf! @[589:zzzz]

我想得到 123 和 589,你如何在 PHP 中使用正则表达式或其他东西?

注意:peterwateber 和 zzzz 只是例子。 应考虑任何随机字符串

不要忘记向前看,这样你就不匹配095032

$foo = '@[123:peterwateber] hello there 095032sdfsdf! @[589:zzzz]';
preg_match_all("/[0-9]+(?=:)/", $foo, $matches);
var_dump($matches[0]); // array(2) { [0]=> string(3) "123" [1]=> string(3) "589" }

以下正则表达式将提取一行中的一个或多个数字字符:

preg_match_all('#'d+#', $subject, $results);
print_r($results);

有一个名为 preg_match_all 的函数

第一个参数接受正则表达式 - 以下示例显示"匹配至少一个数字,后跟任意数量的数字。这将匹配数字。

第二个参数是字符串本身,即要从中提取的主题

第三个是所有匹配元素都将位于其中的数组。所以第一个元素将是 123,第二个元素将是 589,依此类推

    preg_match_all("/[0-9]+/", $string, $matches);