正则表达式,用于从方括号中获取信息 [英] Regex for getting information from square brackets
问题描述
我正在尝试在WordPress中编写类似于短代码的内容,并且正在寻找一个正则表达式,它将使用类似于[title:This is a title]
的内容并将其变为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 is a title]
and turn it to just This is a title
.
如果有人可以提出一种方法来获取类似[code:some code]
之类的东西并将其转换为数组形式的数组,这也将很有用.
大批(
[0] =>'代码'
[1] =>'某些代码')
或者
大批(
'code'=>'某些代码'
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.
谢谢
推荐答案
preg_replace('/\[.*?:(.*?)\]/', '$1', $str);
CodePad .
如果要在冒号之前捕获文本,只需将其用括号括起来,它将成为捕获组1.
If you wanted to capture the text before the colon, simply wrap it in parenthesis and it will become capturing group 1.
我希望使用
preg_match
代替preg_replace
您想使用preg_match_all()
来获取所有匹配项.
You'd want to use preg_match_all()
to get all matches.
preg_match_all('/\[(.*?):(.*?)\]/', $str, $matches);
Idone .
或者,您可以给他们命名的捕获组.
Alternatively, you could give them named capturing groups.
preg_match_all('/\[(?P<identifier>.*?):(?<body>.*?)\]/', $str, $matches);
Idone .
这篇关于正则表达式,用于从方括号中获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!