Mr. Jo
Mr. Jo

Reputation: 5251

How can I build a regex for a rewrite rule in PHP?

I'm currently trying to write a rewrite rule for a url in WordPress. The original URL looks like this:

http://localhost/download/d0RqYU8xek9JOXBsQmJrRGpldWF2QT09/?selected_files%5B0%5D=TURUWEdaWWNtS1ZOd2NSY0MybThCQT09&selected_files%5B1%5D=cWhFVEtlOENNM0VwNmlrUlBmOVF1UT09

The first value after the /download/ is a unique identifier for a specific file store. After that I've added an array of files.

In WordPress I want to write now a rewrite URL for this request so that I can handle it in my backend. For that I need a specific regex that identifies the request and returns matches for building my rewrite url:

public function filter_rewrite_rules_array( $rules ): array {
    $new_rules['download/([0-9][a-z][A-Z]+)/.......'] = admin_url( 'admin-ajax.php' ) . '?download=$matches[1]&selected_files=$matches[2]';
    return array_merge( $rules, $new_rules );
}

The point is that I can't get the regex done.... can someone please help me with this? Even the first match don't works.

Update:

I'm expecting this URL in result:

http://localhost/admin-ajax.php?download=d0RqYU8xek9JOXBsQmJrRGpldWF2QT09&selected_files%5B0%5D=TURUWEdaWWNtS1ZOd2NSY0MybThCQT09&selected_files%5B1%5D=cWhFVEtlOENNM0VwNmlrUlBmOVF1UT09

As I just saw now - the request can have multiple file ids. So no idea how to get this done with a regex. Is this even possible?

Upvotes: 0

Views: 243

Answers (1)

user7571182
user7571182

Reputation:

You may try:

.*?\/download\/(.*?)\/\?(.*)

Explanation of the above regex:

.*? - Lazily matches everything before \download.

\/download\/ - Matches /download/ literally.

(.*?) - Represents a capturing group matching the unique id which you require i.e. matches anything before /? lazily.

(.*) - Represents the second capturing group matching the rest of the part of the url.

The replacement part: Since the part http://localhost/admin-ajax.php?download= is static; you can use the use it along with the captured groups i.e. http://localhost/admin-ajax.php?download=$1&$2.


Picotrial Representation

You can find the demo of the above regex in here.

Upvotes: 1

Related Questions