tags:

views:

74

answers:

6

I am learning regex. I have a very simple question:

I have a long string of content in php.I would like to convert all places where it says:

http://www.example.com/en/rest-of-url

to

http://en.example.com/rest-of-url

Could somebody help me with this? I think I use preg_replace for this?

Bonus: If you have a link to a good site which explains how to do the simplest things like this in regex, please post it. Every regex resource I look at gets very complicated very fast (even the Wikipedia article).

+1  A: 

This is a great site for Regex Tutorials

http://www.regular-expressions.info/ Regex Tutor

Laykes
+1  A: 

http://regexlib.com/

has a nice regular expression cheat sheet and tester

Jimmy
+1  A: 

Assuming:

preg_replace($regex, $replaceWith, $subject); 

$subject is the original text. $regex should be:

'@http://([^\.]*)\.example\.com/en/(.*)@'

$replaceWith should be:

'http://$1.example.com/$2'

EDITED: In my orignial answer, I had missed the fact that you wanted to capture part of the domain name.

Cheeso
You should use a different character for the delimiter instead of `/`, it makes the regex easier to understand.
DisgruntledGoat
+2  A: 

In PHP:

$search = '~http://www.example.com/([^/]+)/(.+)~';
$replace = 'http://$1.example.com/$2';
$new = preg_replace( $search, $replace, $original );
DisgruntledGoat
+1  A: 

This will work with any domainname:

$url = 'http://www.example.com/en/rest-of-url';

echo preg_replace('%www(\..*?/)(\w+)/%', '\2\1', $url);

gives:

http://en.example.com/rest-of-url

Reference: preg_replace

Felix Kling
+1  A: 

You can learn about basic regex, however for your simple question, there's no need for regex.

$str="http://www.example.com/en/rest-of-url";
$s = explode("/",$str);
unset( $s[3]);
print_r( implode("/",$s) ) ;
ghostdog74