php Php用正则表达式查找字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10142658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Php find string with regex
提问by VVV
I've read multiple tutorials on regex but it just won't stick in my head. I can never get my patterns to work. Hope someone can help.
我已经阅读了多个关于正则表达式的教程,但它不会留在我的脑海中。我永远无法让我的模式发挥作用。希望有人能帮忙。
I have a php variable ($content) where I need to find a certain pattern that looks like this
我有一个 php 变量 ($content),我需要在其中找到一个看起来像这样的模式
[gallery::name/of/the/folder/]
[画廊::名称/的/该/文件夹/]
I would like to search:
我想搜索:
- starting with "[gallery::"
- any other character (variable length)
- ending with "]"
So far, in PHP I have:
到目前为止,在 PHP 中我有:
preg_match('/\[gallery\:/', $content, $matches, PREG_OFFSET_CAPTURE);
I can find [gallery: but that's it. I would like to be able to find the rest (:name/of/the/folder/])
我可以找到[画廊:但就是这样。我希望能够找到其余的 (:name/of/the/folder/])
Any help is appreciated! Thanks!
任何帮助表示赞赏!谢谢!
回答by Niet the Dark Absol
Try capturing it:
尝试捕获它:
preg_match("/\[gallery::(.*?)]/",$content,$m);
Now $mis an array:
现在$m是一个数组:
0 => [gallery::/name/of/the/folder/]
1 => /name/of/the/folder/
回答by Tim Hoolihan
change your regex to
将您的正则表达式更改为
'/\[gallery::([A-Za-z\/]+)\]/'
Since I put the folder/path part in parenthesis, you should get a capture group out of it.
由于我将文件夹/路径部分放在括号中,因此您应该从中获取一个捕获组。
回答by sandeep kumar
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

