如何忽略正则表达式中的字符

I do not know how to ignore an item from the ER.

just need to get P1, but this returns /P1.

is possible to just ignore the bar?

$pattern = "#(/P[0-9])?#";

There are two options here:

  • Exclude it from the group, P1 will be the contents in the capture group:

    $pattern = "#/(P[0-9])#";
    
  • Use a lookbehind so that the / isn't even a part of the match, the entire match will be P1:

    $pattern = "#(?<=/)P[0-9]#";
    

Note that I also removed the ? after your group because I don't think you actually want it, this makes the previous element optional so the regex (/P[0-9])? would match literal any string (it would match an empty string if /P[0-9] could not be matched).

With preg_* functions, you can use the \K trick that reset the begin of the match, example:

$pattern = '~/\KP[0-9]~';