简体   繁体   中英

PHP Regex - Issue with forward slashes and alternation

I have a series of URLs like so:

http://www.somesite.com/de/page
http://www.somesite.com/de/another
http://www.somesite.com/de/page/something
http://www.somesite.com/de/page/bar

I need to search the block of text and pull the language and am using a regex like so:

/(de|en|jp)/

I'm trying to find and replace, via preg_replace and including the forward slashes:

/de/
/en/
/jp/

However, this doesn't work and does not include the slashes. I've tried escaping the slashes with \\ , \\\\ . I've tried placing the needle in preg_quote but this breaks the alternation.

I feel like I am missing something very simple here!

edit:

Full function call:

preg_replace("/(de|en|jp)/", "/".$newLang."/", $url);

--

(tagged magento and wordpress as I am trying to solve an issue with unifying the navigation menu when both CMSes are multilingual)

You don't have to use slashes as delimiters, but you have to have some delimiter. Try this:

if( preg_match("(/(de|en|jp)/)",$url,$m)) {
    $lanuage = $m[1];
}

You can use a different delimiter, such as %.

if (preg_match('%/(de|en|jp)/%', $url, $match)) {
    $lang = $match[1];
}

That should help you, just modify what you have :).

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