简体   繁体   中英

replace url using preg_replace php

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 ?

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

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 '[az][az]', 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.

我怀疑在这种情况下,使用str_replace会更快,如下所示:

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

Finally i got a method my thanks to Purpletoucan

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

it's working now i think!

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