views:

18

answers:

1

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 to 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

+4  A: 

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]);
KennyTM
excellent. and what about spaces?
Syom
@Syom: See update.
KennyTM
@KennyTM Thanks man:/
Syom