php regular expression

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sangfroid
Forum Newbie
Posts: 5
Joined: Tue Jun 10, 2008 9:25 am

php regular expression

Post by sangfroid »

Hi
I want to replace every 4th and higher occurence of "." with / in a string.

For eg:

if i have some string like http://www.google.com.news , http://www.google.com.sports, then I would like to have something like http://www.google.com/news and http://www.google.com/sports

How do i do it with regular expression ??
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: php regular expression

Post by requinix »

Fourth and higher? I only see three.

I don't see why people always think regular expressions fix everything. They're powerful, yeah, but they don't fix everything and much of the time they're a bad solution.

Code: Select all

$string = "http://www.google.com.news";
 
$first = strtok($string, ".") and $string2 = $first;
$second = strtok(".") and $string2 .= "." . $second;
$third = strtok(".") and $string2 .= "." . $third;
// $fourth = strtok(".") and $string2 .= "." . $fourth;
$rest = strtok("") and $string2 .= "/" . str_replace(".", "/", $rest);
 
echo $string2;
Hidden "feature": more than one consecutive period in the domain name gets reduced to only one.
Post Reply