User may enter abc.com/ instead of abc.com, so I want to do validation using strchr.
This works but looks strange
if(strrchr($url, "/") == "/"){
$url = substr($url, 0,-1);
echo $url;
}
Is there a better way of doing this?
Yes - using the optional second argument to trim() or rtrim() you can specify a character list to trim off the end of a string.:
$url = rtrim($url, '/');
If the trailing / is present, it will be stripped and the string returned without it. If not present, the string will be returned in its original form.
// URL with trailing /
$url1 = 'example.com/';
echo rtrim($url1, '/');
// example.com
// URL without trailing
$url2 = 'example.com';
echo rtrim($url2, '/');
// example.com
// URL with many trailing /
$url3 = 'example.com/////';
echo rtrim($url3, '/');
// example.com
Add additional characters into the string with '/' if you want to strip whitespace as well, as in rtrim($url, ' /')
If you merely want to test if the last character of the URL was /, you may do so with substr()
if (substr($url, -1) === '/') {
// true
}
Related
I'm working on how to get a custom class into my body tag. I'd like to parse the URI and drop each part of the URI into the class as a separate string. This is a far as I've gotten. I've got the URI parsed and placed into the body class, but as a single string separated by /'s instead of spaces.
Also, I need the IF statement to add "home" if the URI is simply "/". Unfortunately, my current IF statement blows up the whole page. :-(
<?
$url = $_SERVER['REQUEST_URI'];
$url = trim($url, '/');
if $url = '' {
$url = 'home';
}
endif;
?>
<body class="<?=$url?>">
try this
<?
$url = $_SERVER['REQUEST_URI'];
$url = trim($url, '/');
$url = str_replace ("/", " ", $url);
if ($url == '') {
$url = 'home';
}
?>
<body class="<?=$url?>">
I suggest you to use regular expressions.
<?php
$url = $_SERVER['REQUEST_URI'];
$url = trim($url, '/');
if (preg_match("/^\\/?$/", $url)) {
$url = 'home';
}
endif;
?>
"/^\\/?$/" this is regular expression
^ - means beggining of string
$ - means end of string
\\/ - it's / sign, but it has to be escaped by \\
? means that sign before is optional
It will make match when REQUEST_URI will be empty, or it would contain only / sign.
For instance, I need to add http:// to submitted url like :
//www.mydomain.com/images/icon-32.png (double slash at the beginning)
or
www.mydomain.com/images/icon-32.png
Any idea?
This seems to work fine for your problem.
$url = "//mydomain.com/images/icon-32.png";
// or $url = "mydomain.com/images/icon-32.png";
// Checking if string starts with '//'
if(strpos($url, "//")===0){
$url = "http:" . $url;
}else{
// Checking if string doesn't already start with 'http://'
if(!strpos($url, "http://")===0 || strpos($url, "http://")===false)
$url = "http://" . $url;
}
echo $url;
This problem is little complicated since i'm newbee to php encoding.
My site uses utf-8 encoding.
After a lot of tests, i found some solution. I use this kind of code:
function chr_conv($str)
{
$a=array with pattern('%CE%B2','%CE%B3','%CE%B4','%CE%B5' etc..);
$b=array with replacement characters(a,b,c,d, etc...);
return str_replace($a, $b2, $str);
}
function replace_old($str)
{
$a1 = array ('index.php','/http://' etc...);
$a2 = array with replacement characters('','' etc...);
return str_replace($a1, $a2, $str);
}
function sanitize($url)
{
$url= replace_old(replace_old($url));
$url = strtolower($url);
$url = preg_replace('/[0-9]/', '', $url);
$url = preg_replace('/[?]/', '', $url);
$url = substr($url,1);
return $url;
}
function wbz404_process404()
{
$options = wbz404_getOptions();
$urlRequest = $_SERVER['REQUEST_URI'];
$url = chr_conv($urlRequest);
$requestedURL = replace_old(replace_old($url));
$requestedURL .= wbz404_SortQuery($urlParts);
//Get URL data if it's already in our database
$redirect = wbz404_loadRedirectData($requestedURL);
echo sanitize($requestedURL);
echo "</br>";
echo $requestedURL;
echo "</br>";
}
When incoming url is:
/content.php?147-%CE%A8%CE%AC%CF%81%CE%B9-%CE%BC%CE%B5-%CF%80%CF%81%CE%AC%CF%83%CE%B1%28%CE%A7%CE%BF%CF%8D%CE%BC%CF%80%CE%BB%CE%B9%CE%BA%29";
I get:
/content.php?147-psari-me-prasa-choumplik
I want only:
/psari-me-prasa-choumplik
without the content.php?147- before URL.
BUT the most important problem is that I get ENDLESS LOOP instead of correct URL.
What am i doing wrong?
Have in mind that .htaccess solution won't work since i have a lighttpd server, not Apache.
If you need
I am assuming it's not always ?147- that you need to skip. But always after the first hyphen. In which case, before the echo add the following:
$requestedURL = substr($requestedURL, strrpos( $requestedURL , '-') +1 );
This will search for the position of the first hyphen and return that, add one so you skip the hyphen itself, and use that to cut the $requestedURL string up after the hyphen to the end of the string.
If it's always /content.php?127- then replace strrpos( $requestedURL , '-') +1 with the number 17.
I have full URLs as strings, but I want to remove the http:// at the beginning of the string to display the URL nicely (ex: www.google.com instead of http://www.google.com)
Can someone help?
$str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);
echo $str; // www.google.com
That will work for both http:// and https://
You don't need regular expression at all. Use str_replace instead.
str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
Combined into a single operation as follows:
str_replace(array('http://','https://'), '', $urlString);
Better use this:
$url = parse_url($url);
$url = $url['host'];
echo $url;
Simpler and works for http:// https:// ftp:// and almost all prefixes.
Why not use parse_url instead?
To remove http://domain ( or https ) and to get the path:
$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str);
echo $str;
If you insist on using RegEx:
preg_match( "/^(https?:\/\/)?(.+)$/", $input, $matches );
$url = $matches[0][2];
Yeah, I think that str_replace() and substr() are faster and cleaner than regex. Here is a safe fast function for it. It's easy to see exactly what it does. Note: return substr($url, 7) and substr($url, 8), if you also want to remove the //.
// slash-slash protocol remove https:// or http:// and leave // - if it's not a string starting with https:// or http:// return whatever was passed in
function universal_http_https_protocol($url) {
// Breakout - give back bad passed in value
if (empty($url) || !is_string($url)) {
return $url;
}
// starts with http://
if (strlen($url) >= 7 && "http://" === substr($url, 0, 7)) {
// slash-slash protocol - remove https: leaving //
return substr($url, 5);
}
// starts with https://
elseif (strlen($url) >= 8 && "https://" === substr($url, 0, 8)) {
// slash-slash protocol - remove https: leaving //
return substr($url, 6);
}
// no match, return unchanged string
return $url;
}
<?php
// (PHP 4, PHP 5, PHP 7)
// preg_replace — Perform a regular expression search and replace
$array = [
'https://lemon-kiwi.co',
'http://lemon-kiwi.co',
'lemon-kiwi.co',
'www.lemon-kiwi.co',
];
foreach( $array as $value ){
$url = preg_replace("(^https?://)", "", $value );
}
This code output :
lemon-kiwi.co
lemon-kiwi.co
lemon-kiwi.co
www.lemon-kiwi.co
See documentation PHP preg_replace
I use Codeigniter to create a multilingual website and everything works fine, but when I try to use the "alternative languages helper" by Luis I've got a problem. This helper uses a regular expression to replace the current language with the new one:
$new_uri = preg_replace('/^'.$actual_lang.'/', $lang, $uri);
The problem is that I have a URL like this: http://www.example.com/en/language/english/ and I want to replace only the first "en" without changing the word "english". I tried to use the limit for preg_replace:
$new_uri = preg_replace('/^'.$actual_lang.'/', $lang, $uri, 1);
but this doesn't work for me. Any ideas?
You could do something like this:
$regex = '#^'.preg_quote($actual_lang, '#').'(?=/|$)#';
$new_uri = preg_replace($regex, $lang, $uri);
The last capture pattern basically means "only match if the next character is a forward slash or the end of the string"...
Edit:
If the code you always want to replace is at the beginning of the path, you could always do:
if (stripos($url, $actual_lang) !== false) {
if (strpos($url, '://') !== false) {
$path = parse_url($url, PHP_URL_PATH);
} else {
$path = $url;
}
list($language, $rest) = explode('/', $path, 2);
if ($language == $actual_lang) {
$url = str_replace($path, $lang . '/' . $rest, $url);
}
}
It's a bit more code, but it should be fairly robust. You could always build a class to do this for you (by parsing, replacing and then rebuilding the URL)...
If you know what the beginning of the URL will always, be, use it in the regex!
$domain = "http://www.example.com/"
$regex = '#(?<=^' . preg_quote($domain, '#') . ')' . preg_quote($actual_lang, '#') . '\b#';
$new_uri = preg_replace($regex, $lang, $uri);
In the case of your example, the regular expression would become #(?<=^http://www.example.com/)en\b which would match en only if it followed the specified beginning of a domain ((?<=...) in a regular expression specifies a positive lookbehind) and is followed by a word boundary (so english wouldn't match).