开发者

Regex for getting information from square brackets

开发者 https://www.devze.com 2023-03-07 09:00 出处:网络
I\'m attempting to make something like shortcodes in WordPress, and I\'m looking for a regex that will take something like [title:This i开发者_运维问答s a title] and turn it to just This is a title.

I'm attempting to make something like shortcodes in WordPress, and I'm looking for a regex that will take something like [title:This i开发者_运维问答s a title] and turn it to just This is a title.

It would also be useful if someone could suggest a way to take something like [code:some code] and turn that into an array in the form of array( [0] => 'code' [1] => 'some code') or array( 'code' => 'some code'

I've tried a few different regexes I've found here and there, but none of them seem to work.

Thanks


preg_replace('/\[.*?:(.*?)\]/', '$1', $str);

CodePad.

If you wanted to capture the text before the colon, simply wrap it in parenthesis and it will become capturing group 1.

Update

I'm looking to use preg_match instead of preg_replace

You'd want to use preg_match_all() to get all matches.

preg_match_all('/\[(.*?):(.*?)\]/', $str, $matches);

Ideone.

Alternatively, you could give them named capturing groups.

preg_match_all('/\[(?P<identifier>.*?):(?<body>.*?)\]/', $str, $matches);

Ideone.

0

精彩评论

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