0

I'm using a regex to check a string for a certain format.

preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);

Using this regex, the posted string needs to have this format:

/answer n x

n -> an integer > 0

x -> a string, 512 chars maximum

Now how to extract "n" and "x" the easiest way using PHP? For example:

/answer 56 this is my sample text

Should lead to:

$value1 = 56;
$value2 = "this is my sample text";
4
  • What is there in $hit? Commented Jul 3, 2017 at 20:12
  • $hit is empty. Not necessary. Commented Jul 3, 2017 at 20:13
  • 1
    $hit stores matches. Have you printed it after preg_match? Commented Jul 3, 2017 at 20:16
  • No need to use PREG_OFFSET_CAPTURE then just access $hit[1] and $hit[2]. Commented Jul 3, 2017 at 20:51

1 Answer 1

1

Running this simple piece of code

<?php
$hit = [];
$str = '/answer 56 this is my sample text';
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
echo'<pre>',print_r($hit),'</pre>';

Will show you, that $hit has following values:

<pre>Array
(
    [0] => Array
        (
            [0] => /answer 56 this is my sample text
            [1] => 0
        )

    [1] => Array
        (
            [0] => 56
            [1] => 8
        )

    [2] => Array
        (
            [0] => this is my sample text
            [1] => 11
        )

)
1</pre>

Here:

  • $hit[0][0] is full string that matches your pattern
  • $hit[1][0] is a substring that matches pattern [1-9][0-9]*
  • $hit[2][0] is a substring that matches pattern .{1,512}

So,

$value1 = $hit[1][0];
$value2 = $hit[2][0];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.