如何从字符串的某个部分中的字符串中获取未知数字?

时间:2015-05-14 07:43:59

标签: php regex string

我的字符串:

How would you rate the ease and comfort required to undertake the session?@QUESTION_VALUE_0

我如何才能从上面的字符串中获取此值?我不知道这个值是什么(除了它将是一个整数):

(some question)@QUESTION_VALUE_X其中X是一个整数,我想得到X。

我看了正则表达式,但是我对正则表达式感到厌烦,所以我不知所措,欢呼你们!

关于我使用正则表达式的内容

/@QUESTION_VALUE_[0-9]+/

但是我无法从字符串中获取数字。我怎么才能抓住号码?

1 个答案:

答案 0 :(得分:2)

这应该适合你:

只需将escape sequence \ d (表示 0-9 )与quantifier + 放在一起(这意味着 1次或更多次)进入())以捕获您可以在数组中访问的数字{{ 1}}。

$m

输出:

<?php

    $str = "How would you rate the ease and comfort required to undertake the session?@QUESTION_VALUE_0";
    preg_match("/@QUESTION_VALUE_(\d+)/", $str, $m);
    echo $m[1];

?>

如果你0 ,你会看到阵列的结构:

print_r($m);

现在你看到^你在第一个元素中有完全匹配,然后在第二个元素中有第一个组((\ d +))。