Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取匹配元素的内容_Php_Regex_Preg Match - Fatal编程技术网

Php 获取匹配元素的内容

Php 获取匹配元素的内容,php,regex,preg-match,Php,Regex,Preg Match,我有一根绳子 $str = "this is [start] my string [end] at this moment"; 我需要在[start]和[end]中获取内容 当我使用 $result = preg_match('/\[start\].+\[end\]/',$str, $m); 它改变了[start]我的字符串[end],但我只需要获取我的字符串(不带空格) 当然,我可以让另一个preg_替换并删除它们,但我认为必须有更优雅的解决方案 感谢使用捕获的组 $result = pr

我有一根绳子

$str = "this is [start] my string [end] at this moment";
我需要在
[start]
[end]
中获取内容

当我使用

$result = preg_match('/\[start\].+\[end\]/',$str, $m);
它改变了
[start]我的字符串[end]
,但我只需要获取
我的字符串
(不带空格)

当然,我可以让另一个preg_替换并删除它们,但我认为必须有更优雅的解决方案

感谢使用捕获的组

$result = preg_match('/\[start\](.+)\[end\]/',$str, $m);
$matched = $m[1];
(请注意,如果存在多个
[start]
/
[end]
组(需要惰性量词
+?
),或嵌套的
[start]
/
[end]
组(使用递归模式),则正则表达式将失败。)


如果不需要空格,可以避免在正则表达式中匹配:

$result = preg_match('/\[start\]\s*(.+?)\s*\[end\]/',$str, $m);
$matched = $m[1];
或者只需调用
trim()

使用捕获的组

$result = preg_match('/\[start\](.+)\[end\]/',$str, $m);
$matched = $m[1];
(请注意,如果存在多个
[start]
/
[end]
组(需要惰性量词
+?
),或嵌套的
[start]
/
[end]
组(使用递归模式),则正则表达式将失败。)


如果不需要空格,可以避免在正则表达式中匹配:

$result = preg_match('/\[start\]\s*(.+?)\s*\[end\]/',$str, $m);
$matched = $m[1];
或者只需调用
trim()