开发者

How to cut from a string by reg ex [str] someth [/str] blocks?

Ex: 开发者_StackOverflow社区I have a string "my str [str]string string[/str] my str [str]string string[/str] kjnvjsfn" I`ve tried to do so with RegExp like this

preg_match_all('/\[str](.|\n|\r\n)*\[\/str\]/', $str, $arr);

but it cuts whole string till last [/str] Thanks.


Make it non-greedy: Use *? instead of *

preg_match_all('/\[str](.|\n|\r\n)*?\[\/str\]/', $str, $arr);

However, regexes are probably not the best way to go. I.e., it may be sufficient for your purpose (if you're e.g. writing them yourself). But if "tags" can be nested then you'll find that the regex approach is becoming very cumbersome.


Try making your regex non-greedy:

preg_match_all('/\[str](.*?)\[\/str\]/s', $str, $arr);


Yes, that is because the * is greedy. Try use the non greedy *?

preg_match_all('/\[str](.|\n|\r\n)*?\[\/str\]/', $str, $arr);


You can use the m and s modifiers to simplify you expression

preg_match_all('/\[str\](.*?)\[\/str\]/ms', $str, $arr);

This expression is non-greedy and will match anything between [str] and [/str] even if it goes over multiple lines so you don't need to match \r or \n

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜