简体   繁体   English

在PHP Regex中需要帮助

[英]Need Help in PHP Regex

I am studying about regex, i figured out some about matching one or more character, but i have a case, but don't know how to solve this.. 我正在研究正则表达式,我想出了一些关于匹配一个或多个角色,但我有一个案例,但不知道如何解决这个问题。

For example i have: 例如我有:

$data = "bla bla -start- blu blu blu -end- bla bla";
$pattern = "/\-start\-[\w]\-end\- /";
preg_match($pattern, $data, $matches);
print_r($matches);

i intend to take anything between '-start-' and '-end-', so i expect to get 我打算在'-start-'和'-end-'之间取任何东西,所以我希望得到
' blu blu blu '. '蓝光蓝光'。
any suggestion ? 有什么建议吗?

\\w represents only word characters, and you need to also allow for spaces. \\w仅代表单词字符,您还需要允许空格。 Assuming you really want to allow anything in between -start- and -end- you can use . 假设你真的想在-start--end-之间允许任何东西 - 你可以使用. which matches any character. 匹配任何角色。

Hyphens need not be escaped unless enclosed in a character pattern (between square brackets [ and ] ), so you can replace \\- with just - . 连字符不需要转义,除非用字符模式(方括号[]之间)括起来,所以你可以用\\-替换\\- -

Just like using a single \\w represents matching any single word character, . 就像使用单个\\w表示匹配任何单个单词字符一样. represents matching any single character, so you need to add some more information in. Following either of these with + would indicate matching at least one character, or with a * would indicate zero or more characters. 表示匹配任何单个字符,因此您需要添加更多信息。以下任何一个用+表示匹配至少一个字符,或用*表示零个或多个字符。 Assuming you want at least one character, your expression should be okay like this: 假设你想要至少一个角色,你的表达应该是这样的:

$pattern = "/-start-(.+)-end- /";

Supposing you might encounter an expression like: -start- foo -end- -end- and you want to terminate on the first -end- (the content to extract is foo ), then you need to operate in a non-greedy way. 假设您可能遇到如下表达式: -start- foo -end- -end-并且您想要在第一个-end-终止(要提取的内容是foo ),那么您需要以非贪婪的方式操作。 PHP's regex is greedy by default, to turn this off, you follow the + (or a * ) with a ? 默认情况下PHP的正则表达式是贪婪的,关闭它,你跟着+ (或a * )一个? , like this: , 像这样:

$pattern = "/-start-(.+?)-end- /";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM