我正在使用正则表达式检查字符串是否有某种格式。
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
使用此正则表达式,发布的字符串需要具有以下格式:
/ answer n x
n - >整数> 0
x - >一个字符串,最多512个字符
现在如何提取" n"和" x"使用PHP的最简单方法? 例如:
/ answer 56这是我的示例文本
应该导致:
$value1 = 56;
$value2 = "this is my sample text";
答案 0 :(得分:1)
运行这段简单的代码
<?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>';
将告诉您,$hit
具有以下值:
<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>
下面:
$hit[0][0]
是与您的模式匹配的完整字符串$hit[1][0]
是匹配模式[1-9][0-9]*
$hit[2][0]
是匹配模式.{1,512}
所以,
$value1 = $hit[1][0];
$value2 = $hit[2][0];