开发者

get the content of matched element

i have a string

$str = "this is [start] my string [end] at this moment";

i need to get the content within [start] and [end].

when i use

$result = preg_match('/\[start\].+\[end\]/',$str, $m);

it mutches [start] my string [end], but i need 开发者_如何学Pythonto get only my string(without spaces).

sure i can make another preg_replace and delete them, but i think there must be more elegant solution.

Thanks


Use captured groups.

$result = preg_match('/\[start\](.+)\[end\]/',$str, $m);
$matched = $m[1];

(Note that your regex will fail if there are multiple [start]/[end] groups (needs lazy quantifier .+?), or nested [start]/[end] groups (use recursive pattern).)


If you don't want the spaces, you could avoid matching it in the regex:

$result = preg_match('/\[start\]\s*(.+?)\s*\[end\]/',$str, $m);
$matched = $m[1];

or just call trim().

$result = preg_match('/\[start\](.+)\[end\]/',$str, $m);
$matched = trim($m[1]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜