Reputation: 131
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";
Upvotes: 0
Views: 31
Reputation: 54841
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];
Upvotes: 1