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:

Read More
/(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)

Related posts

Leave a Reply

2 comments

  1. 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];
    }
    
  2. 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 :).