简体   繁体   中英

PHP replace regex with pattern inside subject string

I'm not really sure how to word the title but I'm trying to achieve the following:

$string = 'category/(.*)/page/([0-9]+)' and I need to turn that into category/test/page/2 by means of passing an array of parameters like so:

Array
(
    [0] => test
    [1] => 2
)

Doing $string = preg_replace('#^'.$string.'$#', $replacements, $string) results in an error about $replacements being an array, which matches what the documentation says, however I'm not sure how else to go about it.

I can't really get my head around the pattern and subject begin the same string.

You'll have a make a new regex to match what you want in the string. You'll have to make something that matches the literal strings (.*) and ([0-9]+) . Something like this, perhaps:

/(.+)\/(\(.+\))\/(.+)\/(\(.+\))/

Then you can try to do this:

$string = preg_replace('/(.+)\/(\(.+\))\/(.+)\/(\(.+\))/', '$1/test/$3/2', $string);

Or using $replacements :

$string = preg_replace(
    '/(.+)\/(\(.+\))\/(.+)\/(\(.+\))/',
    '$1/'.$replacements[0].'/$3/'.$replacements[1],
    $string
);

DEMO: https://eval.in/435153

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM