开发者

Add root folder onto URL Using Regex

开发者 https://www.devze.com 2023-04-10 10:09 出处:网络
I\'m tryi开发者_Python百科ng to transform any URL in PHP and add a root folder onto it using regex.

I'm tryi开发者_Python百科ng to transform any URL in PHP and add a root folder onto it using regex.

Before:

http://domainNamehere.com/event/test-event-in-the-future/

After:

http://domainNamehere.com/es/event/test-event-in-the-future/

Any ideas?


A simple solution without regex:

$root_folder = 'es';
$url = "http://domainNamehere.com/event/test-event-in-the-future/";

$p = strpos($url, '/', 8);
$url_new = sprintf('%s/%s/%s', substr($url, 0, $p), $root_folder, substr($url, $p+1));

EDIT: JavaScript solution is pretty much the same:

var root_folder = 'es';
var url = "http://domainNamehere.com/event/test-event-in-the-future/";

var p = url.indexOf('/', 8);
var url_new = url.substring(0,p) + '/' + root_folder + url.substring(p);

Of course, for a live application you should also check if p actually gets a valid value assigned (that means if the slash is found) because you might have an invalid url in your input or empty string.


$url = 'http://domainNamehere.com/event/test-event-in-the-future/'; //or the function you use to grab it;
$url = str_replace('domainNamehere.com','domainNamehere.com/es', $url);

quite dirty but effective and without regex, assuming your "es" folder is always in that position (I think so)


If the domain name is always the same you can use:

$string = str_replace('domainNamehere.com', 'domainNamehere.com/es', $url);


Untested:

$url = preg_replace('#(?<=^[a-z]+://[^/]+/)#i', "es/", $url);

Use '#' to delimit the regular expression so the slashes don't have to be escaped.

(?<=...) searches for a match for [a-z]://[^/]+/ without including it in the matched string.

[a-z]+://[^/]/ matches a sequence of letters followed by :// followed by non-slashes, then a slash. This will handle all web protocols, particularly http and https.

The little i makes the search case-insensitive.

The replacement just inserts es/ after the match.


This is the most succinct way that I could think of how to do it.

$new_url = preg_replace('#(?<=\w)(?=/)#', '/en', $url, 1);

It will insert whatever you put in the 2nd parameter into the string just before the first slash that also has a proceeding alphanumeric character.

Tested with PHP 5.3.6

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号