0

Hi all i know preg_replace can be used for formatting string but i need help in that concerned area my url will be like this

www.example.com/en/index.php

or

www.example.com/fr/index.php

what i want is to get

result as

www.example.com/index.php

i need it in php code so as to set in a session

can anyone please explain how ?

0

4 Answers 4

1

preg_replace('/www.example.com\/(.+)\/index.php/i', "www.example.com/index.php?lang=$1", $url); will do the thing

Sign up to request clarification or add additional context in comments.

7 Comments

why do you use brackets there?
I thought the OP might need the captured language code, so I added the capturing brackets. Of course I should change the code to reflect how one can access that later.
Sorry, I forgot the delimiters
hi another prob if i have some thing like this what to do? www.example.com/en/test1/page.php this is not working for that
so, basically what you need is anything in form of example.com/language/something/something/something to be converted into example.com/something/something/something? You can trypreg_replace('/www.example.com\/(.*)\/i', "www.example.com/", $url);
|
1

This is one way to do it:-

$newurl = preg_replace('/\/[a-z][a-z]\//', '/', $url);

Note that the search string appears with quotes and forward slashes ('/.../') and that the forward slashes in the URL then have to be escaped (\/). The language code is then matched with '[a-z][a-z]', but there are several other ways to do this and you may want something more liberal in case there are ever 3 letter codes, or caps. Equally you may need to do something tighter depending on what other URL schemes might appear.

1 Comment

sorry here it may also be www.example.com/esp/index.php
1

I suspect in this instance it would be faster simply to use str_replace as follows:

$cleanedData = str_replace(array('www.example.com/en/', 'www.example.com/fr/'), '', $sourceData);

Comments

0

Finally i got a method my thanks to Purpletoucan

$newurl = preg_replace('/\/(en|esp|fr)\//', '/', $url);

it's working now i think!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.