简体   繁体   English

PHP正则表达式获取斜线之间的4个字符串的结果

[英]Php regex to get results of 4 strings between slashes

I'm having troubles with regex. 我在使用正则表达式时遇到了麻烦。 I'm trying to isolate query results that are like : 我正在尝试隔离如下查询结果:

string1/string2/string3/string4

string1/string2/string3/string4/string5

I want to find the first case from the two above, the one with the chain ending after "string4". 我想从上面的两个中找到第一种情况,即链在“ string4”之后结尾的情况。 I've tryied this regex that doesn't actually works : 我尝试过这个实际上不起作用的正则表达式:

$my_regex = "/^(.+)\/(.+)\/(.+)\/(.+)$/";
if (preg_match($my_regex, $category->name)) {
     ...
}

Am I missing something ? 我想念什么吗?

Don't use a regex, use explode() function 不要使用正则表达式,请使用explode()函数

$pieces = explode("/", $your_string); //pieces will be an array
foreach($pieces as $piece) {
   [...]
}

With a regex, a solution could be : 使用正则表达式,解决方案可以是:

$my_regex = "/^([^\/]+\/){3}[^\/]+$/";
if (preg_match($my_regex, $category->name)) {
     ...
}

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

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