简体   繁体   中英

How can I get a unknown number from a string within a certain part of the string?

My string:

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

How would I be able to get this value specifically from the above string? I don't know what this value will be (apart from that it will be an integer):

(some question)@QUESTION_VALUE_X where X is an integer, I want to get X.

I looked into Regex, but I suck at regular expressions, so I'm at a loss, cheers guys!

About as far as I got with regex

/@QUESTION_VALUE_[0-9]+/

But I can't get the number out of the string. How can I only grab the number?

This should work for you:

Just put the escape sequence \\d (which means 0-9 ) with the quantifier + (which means 1 or more times ) into a group ( () ) to capture the the number which you then can access in the array $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];

?>

output:

0

If you do print_r($m); you will see the structure of your array:

Array
(
    [0] => @QUESTION_VALUE_0
    [1] => 0
)

And now you see ^ that you have the full match in the first element and then first group ( (\\d+) ) in the second element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM