将网址与字母数字,短划线和下划线字符匹配?

How can I match the following function with the segment in the middle ("/(\w+)\") to allow URL characters like alphanumerics & _.- ?

if(preg_match('/^\/segment1\/(\w+)\/segment2/', '/segment1/aAbB0123.-_Z/segment2', $match)) {                       
    print_r($match);
    /*
    * Array
    (
        [0] => /segment1/s/segment2
        [1] => aAbB0123.-_Z
    )
    *
}

There's one other issue with your pattern, it's requiring a forward slash at the end, whereas your input does not have one. I wouldn't even make it optional, just leave it out altogether, you can't get more optional than that.

Is your goal here to Validate, or to Capture that middle segment? I'm assuming capture since in your example there would be no other reason to have a sub-expression. Giving a couple exact input examples and what you actually require would be best.

So, you have a few options.

Super lazy:

segment1/(.*?)/segment2

One Sub-Segment, also Super lazy:

segment1/([^/]+)/segment2

Exact Requirements (Find out what you want in a URL, I'm pretty sure some of those characters you listed aren't allowed in a URL, just in the Querystring):

segment1/([-\w&.%=#]+)/segment2

Allow Multiple Segments, Lazy:

segment1/((?:[^/]+/?)+)/segment2

Allow Multiple Segments, Exact Requirements:

segment1/((?:[-\w&.%=#]+/?)+)/segment2

Depending on your settings, you may need to escape some things.