views:

35

answers:

1

Hello.

I have two strings like:

http://localhost/web/

and

http://localhost/web/category/

which sometimes become:

http://localhost/web/2/, http://localhost/web/3/ etc....

and

http://localhost/web/category/2/, http://localhost/web/category/3/ etc...

I want to make a verification and:

If the link is http://localhost/web/ it remains the same.

If the link is http://localhost/web/2/ it becomes http://localhost/web/

If the link is http://localhost/web/category/ it remains the same.

If the link is http://localhost/web/category/2/ it becomes http://localhost/web/category/

I guess it should be done using preg_replace() and preg_match().

How can I do it?

Thanks.

+2  A: 

The following is the regular expression you will need:

(http:\/\/localhost\/)(web|web\/category)\/([\d]+)\/

For the preg_replace function, you will need a replacement statement which will re-write the string based on your criteria:

'$1$2'

The above replacement statement essentially concatenates the first capture group (first set of parens which evaluates to http://localhost/) with the second capture group of either 'web' or 'web/category'. Since we don't care about the last capture group ($3), we don't add it to the replacement statement; however, we could since we are capturing it. If you don't want to capture it, replace this "([\d]+)" with "[\d]+".

The following is sample code which incorporates the pattern with the replacement to form a full preg_replace statement:

<?php

$pattern = '@(http:\/\/localhost\/)(web|web\/category)\/([\d]+)\/@i';

$subjects = array(
    'http://localhost/web/2/',
    'http://localhost/web/category/2/'
);

foreach ($subjects as $subject) {
    echo sprintf('Original: %s, Modified: %s', $subject, preg_replace($pattern, '$1$2', $subject)), PHP_EOL;
}

Toss the above code into a file (for example: replace.php) and run it via the command-line:

php replace.php
wilmoore
excellent! that's what I need. thanks a lot!
mohamed87