PHP字符串如何将模式后的部分提取到单独的变量中

I have a string that collects two pieces of information. Everything before the slash is a search variable, and everything after is the page number.

Assume the following:

$search = "classic rock/8"

should be $searchvalue[0]='classic $searchvalue[1]='rock' $searchvalue[x]= etc... and then $page=8

I tried a few approaches, the last one is to do three passes by first removing everything after the slash.

$search=substr($search, 0, strpos($search, '/'));

and then separate the $search values into an array. and then go back (a 3rd time!) and get the page variable by deleting everything before the slash.

I know this is highly inefficient. Is there a way to do these actions in one pass?

Thanks in advance!

You can explode that string twice and get the same results!

$res = explode("/", $search); 
$page = $res[1]; //This is the page

$searchValues = explode(" ", $res[0]); //These are the results

You can use strrpos:

$search = 'classic rock/8';
$page = substr($search, strrpos($search, '/')+1); // 8

In response to getting it in one pass, you can use the preg match all function or
you can use the preg split function.

Either way has its drawbacks, but so does explode and strrpos or anything else.

A lot of people don't realize they can use preg split in a much more detailed way
to precisely carve up a string. This can be done by defining splits in detail to include captures. Its a little different this way, but has big power if you learn how to do it.

Regex:

  #  ([^\s\/]+)(?:\s+|$)|\/+\s*(\d+)[\s\/]*$|\/.*$

                       # Delim-1
     ( [^\s\/]+ )      # (1), A group of not whitespace nor forward slash
     (?: \s+ | $ )     # folowed by whitespace or EOL

                       # Delim-2
  |  \/+ \s*           # Forward slashes folowed by whitespaces
     ( \d+ )           # (2), folowed by a group of digits
     [\s\/]* $         # followed by whitespaces or slashes until EOL

                       # Delim-3
  |  \/ .* $           # Forward slash folowed by anything until EOL

PHP code:

 <?php
 $keywords = preg_split
     ( 
         "/([^\s\/]+)(?:\s+|$)|\/+\s*(\d+)[\s\/]*$|\/.*$/",
         "classic rock/8",
         -1,
         PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE 
     );
 print_r($keywords);
 ?> 

 Result:
 Array
 (
     [0] => classic
     [1] => rock
     [2] => 8
 )