admin管理员组文章数量:1426950
I noticed that often in register_rest_routes, are used regexp like ?P<lang>
, ?P<category_id>\d+
and so on, but I guess it's not standard regexp syntax. What exactly does it do?
I noticed that often in register_rest_routes, are used regexp like ?P<lang>
, ?P<category_id>\d+
and so on, but I guess it's not standard regexp syntax. What exactly does it do?
1 Answer
Reset to default 3It's called a path variable:
Path variables enable us to add dynamic routes.
See below example taken from the REST API handbook:
// Here we are registering our route for single products. The (?P<id>[\d]+) is
// our path variable for the ID, which, in this example, can only be some form
// of positive number.
register_rest_route( 'my-shop/v1', '/products/(?P<id>[\d]+)', array(
...
'callback' => 'prefix_get_product',
) );
The important part to note is that in the second route we register (the one above), we add on a path variable
/(?P<id>[\d]+)
to our resource path/products
. The path variable is a regular expression. In this case it uses[\d]+
to signify that should be any numerical character at least once. If you are using numeric IDs for your resources, then this is a great example of how to use a path variable. When using path variables, we now have to be careful around what can be matched as it is user input.
And the format is: ?P<{name}>{regex pattern}
.
And based on the above example, one could go to http://example/wp-json/my-shop/v1/products/123
to retrieve a single resource.
PS: I edited mainly to add the second paragraph above.
本文标签:
版权声明:本文标题:regex - What's the "?P<tag>" register rest api construct, what is for and where to find 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745467783a2659607.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论