简体   繁体   中英

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". 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

$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)) {
     ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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