Slug URL generation function overriding the Ç - php

I have this function above to create url slugs from posts title, the problem is that the ç characther is not being converted to c. It is actually being override by the function.
Example post title: Coração de Pelúcia
The slug generated: coraao-de-pelucia
How can i fix this function to generate the slug like: coracao-de-pelucia
function generate_seo_link($input,$replace = '-',$remove_words = true,$words_array = array())
{
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
$return = trim(ereg_replace(' +',' ',preg_replace('/[^a-zA-Z0-9\s]/','',strtolower($input))));
//remove words, if not helpful to seo
//i like my defaults list in remove_words(), so I wont pass that array
if($remove_words) { $return = remove_words($return,$replace,$words_array); }
//convert the spaces to whatever the user wants
//usually a dash or underscore..
//...then return the value.
return str_replace(' ',$replace,$return);
}

You should use the iconv module and a function such as this one to do the conversion:
function url_safe($string){
$url = $string;
setlocale(LC_ALL, 'pt_BR'); // change to the one of your language
$url = iconv("UTF-8", "ASCII//TRANSLIT", $url);
$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url);
$url = trim($url, "-");
$url = strtolower($url);
return $url;
}

Related

text to link, problem with link that has not https

Users can add texts. This texts can have links.
I'd like do add click to it.
The problem is, some links works like:
http://www.example.com
links that has no http will not work and will become:
http://mywebsite.com/www.example.com
any ideas how to solve it?
function toLink($titulo){
$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$titulo = preg_replace($url, '$0', $titulo);
return $titulo;
}
Use preg_replace_callback instead and you can interrogate the match to see if you need to add the protocol.
function toLink($titulo) {
$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$titulo = preg_replace_callback($url, function($matches) {
$url = $matches[0];
if (!preg_match('/^https?:\/\//', $url)) $url = 'http://'.$matches[0];
''.$url.'';
}, $titulo);
return $titulo;
}

$_SERVER['QUERY_STRING'] become empty if the url change

I have a problem to resolve. The first url allow me to display information or not on the website. It work fine.
I identify Account&Edit for example and make action.
http://localhost/boutique/index.php?Account&Edit
$_SERVER['QUERY_STRING'] = Account&Edit
If I rewrite the url, the system does not work and Account&Edit become Account/Edit
http://localhost/boutique/index.php/Account/Edit
$_SERVER['QUERY_STRING'] = '';
How to resolve this element when this element Account&Edit change ?
$_SERVER['QUERY_STRING'] is empty is this case.
Thank you.
I make that to solve the problem.
public function getUrlwithoutSEFU() {
if (empty($_SERVER['QUERY_STRING'])) {
$url = $_SERVER['REQUEST_URI'];
$replace = str_replace('index.php', '', $url);
$replace = str_replace(CLICSHOPPING::getConfig('http_path'), '', $replace);
$replace = substr($replace, 1);
$replace = str_replace('/', '&', $replace);
$url_string = $replace;
} else {
$url_string = $_SERVER['QUERY_STRING'];
}
return $url_string;
}
Take a look at RFC3875: The Common Gateway Interface (CGI) Version 1.1
When you have no ? i nthe request URL, then there's no query string.
Looking at REQUEST_URI would make sense.
This is how request urls are split into environment vars:
# QUERY_STRING
# ↓↓↓↓↓↓↓↓↓↓↓↓
http://localhost/boutique/index.php?Account&Edit
Or the part after the (directly invoked) php script. (This may vary depending on SAPI or be impacted by rewrite rules).
# PATH_INFO
# ↓↓↓↓↓↓↓↓↓↓↓↓↓
http://localhost/boutique/index.php/Account/Edit
Or the full path:
# REQUEST_URI
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
http://localhost/boutique/index.php/Account/Edit
Notably you would have to split it up yourself then. Also may show up as REDIRECT_REQUEST_URI for example in the $_SERVER array with some setups.
Solution
public function getUrlwithoutSEFU() {
if (empty($_SERVER['QUERY_STRING'])) {
$url = $_SERVER['REQUEST_URI'];
$replace = str_replace('index.php', '', $url);
$replace = str_replace(CLICSHOPPING::getConfig('http_path'), '', $replace);
$replace = substr($replace, 1);
$replace = str_replace('/', '&', $replace);
$url_string = $replace;
} else {
$url_string = $_SERVER['QUERY_STRING'];
}
return $url_string;
}

finding the last occurrence of a string and replacing it

I have the following link as a string in php:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
I am trying to add the word BIG before the number so at the end I will have:
$url = 'http://www.example.com/assets/images/temp/big10.jpg';
I am currently accomplishing that by using explode on / then adding big to the last array. My only issue is that in the future, this link might have less / i.e.: http://www.example.com/assets/10.jpg. In this case, my explode statement will not work. Is there a better way to add the word big after the last occurance of /?
I also came up with this method:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$filename = substr(strrchr($url, "/"), 1); // returns 10.jpg
$newfilename = 'big'.substr(strrchr($url, "/"), 1); // returns big10.jpg
$newurl = str_replace($filename,$newfilename,$url); // replaces 10.jpg with big.jpg
According to description as mentioned into above question as a solution to it please try executing following code snippet .
<?php
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$fileName = basename($url);
$newFileName = 'big' . $fileName;
$url = str_ireplace($fileName, $newFileName, $url);
echo $url;
?>
Explode will always work. However, if you want a neater way to do it you can do this:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$newurl = substr_replace($url, "big", strrpos($url, '/') + 1, 0);
This will give your expected result: http://www.example.com/assets/images/temp/big10.jpg
There are quite a few methods to accomplish what you're wanting.
To me the easiest would be to use pathinfo to extract the filename, and then append your prefix to the basename.
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$pathinfo = pathinfo($url);
var_dump($pathinfo['dirname'] . '/' . $prefix . $pathinfo['basename']);
Result: https://3v4l.org/3MkIG
string(51) "http://www.example.com/assets/images/temp/big10.jpg"
Object oriented approach: https://3v4l.org/aF5lf
class FileNamePrefixer extends SplFileInfo
{
public function addPrefix($prefix)
{
return $this->getPathInfo() . '/' . $prefix . $this->getBaseName();
}
}
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$fileInfo = new FileNamePrefixer($url);
var_dump($fileInfo->addPrefix('big'));
Another method is to use preg_replace to specify a pattern of words you want to replace.
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$new_url = preg_replace('/([\w|\s|-]+)(\.\w+)$/', $prefix . '$1$2', $url);
var_dump($new_url);
The pattern ([\w|\s|-]+)(\.\w+)$ means; at the end of the string, look for a word (characters: a-z, A-Z, 0-9, _, space, and -), followed by a period, which is followed by another word and store them in variables $1 and $2.
Result: https://3v4l.org/6e8d7
string(51) "http://www.example.com/assets/images/temp/big10.jpg"
Note that if your URL will optionally contain fragments or a querystring, the preg_replace pattern above will not work. Instead you would need to account for them as optional like so:
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg?foo=bar&baz=foo#foobar';
$new_url = preg_replace('/([\w|\s|-]+)(\.\w+)(\?.+)?(#.+)?$/', $prefix . '$1$2$3$4', $url);
var_dump($new_url);
The pattern (\?.+)?(#.+)? means; optionally find ? followed by anything, and optionally find # followed by anything and store them in variables $3 and $4 with the original pattern.
Result: https://3v4l.org/uuYrO
string(74) "http://www.example.com/assets/images/temp/big10.jpg?foo=bar&baz=foo#foobar"

Remove "http://" from URL string

I am using a bit.ly shortener for my custom domain. It outputs http://shrt.dmn/abc123; however, I'd like it to just output shrt.dmn/abc123.
Here is my code.
//automatically create bit.ly url for wordpress widgets
function bitly()
{
//login information
$url = get_permalink(); //for wordpress permalink
$login = 'UserName'; //your bit.ly login
$apikey = 'API_KEY'; //add your bit.ly APIkey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//generate the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//fetch url
$response = file_get_contents($bitly);
//for json formating
if(strtolower($format) == 'json')
{
$json = #json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //for xml formatting
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
As long as it is supposed to be url and if there is http:// - then this solution is the simplest possible:
$url = str_replace('http://', '', $url);
Change your following line:
echo $json['results'][$url]['shortUrl'];
for this one:
echo substr( $json['results'][$url]['shortUrl'], 7);
You want to do a preg_replace.
$variable = preg_replace( '/http:\/\//', '', $variable ); (this is untested, so you might also need to escape the : character ).
you can also achieve the same effect with $variable = str_replace('http://', '', $variable )

Best way to convert title into url compatible mode in PHP?

http://domain.name/1-As Low As 10% Downpayment, Free Golf Membership!!!
The above url will report 400 bad request,
how to convert such title to user friendly good request?
You may want to use a "slug" instead. Rather than using the verbatim title as the URL, you strtolower() and replace all non-alphanumeric characters with hyphens, then remove duplicate hyphens. If you feel like extra credit, you can strip out stopwords, too.
So "1-As Low As 10% Downpayment, Free Golf Membership!!!" becomes:
as-low-as-10-downpayment-free-gold-membership
Something like this:
function sluggify($url)
{
# Prep string with some basic normalization
$url = strtolower($url);
$url = strip_tags($url);
$url = stripslashes($url);
$url = html_entity_decode($url);
# Remove quotes (can't, etc.)
$url = str_replace('\'', '', $url);
# Replace non-alpha numeric with hyphens
$match = '/[^a-z0-9]+/';
$replace = '-';
$url = preg_replace($match, $replace, $url);
$url = trim($url, '-');
return $url;
}
You could probably shorten it with longer regexps but it's pretty straightforward as-is. The bonus is that you can use the same function to validate the query parameter before you run a query on the database to match the title, so someone can't stick silly things into your database.
See the first answer here URL Friendly Username in PHP?:
function Slug($string)
{
return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}
$user = 'Alix Axel';
echo Slug($user); // alix-axel
$user = 'Álix Ãxel';
echo Slug($user); // alix-axel
$user = 'Álix----_Ãxel!?!?';
echo Slug($user); // alix-axel
You can use urlencode or rawurlencode... for example Wikipedia do that. See this link:
http://en.wikipedia.org/wiki/Ichigo_100%25
that's the php encoding for % = %25
I just create a gist with a useful slug function:
https://gist.github.com/ninjagab/11244087
You can use it to convert title to seo friendly url.
<?php
class SanitizeUrl {
public static function slug($string, $space="-") {
$string = utf8_encode($string);
if (function_exists('iconv')) {
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
}
$string = preg_replace("/[^a-zA-Z0-9 \-]/", "", $string);
$string = trim(preg_replace("/\\s+/", " ", $string));
$string = strtolower($string);
$string = str_replace(" ", $space, $string);
return $string;
}
}
$title = 'Thi is a test string with some "strange" chars ò à ù...';
echo SanitizeUrl::slug($title);
//this will output:
//thi-is-a-test-string-with-some-strange-chars-o-a-u
You could use the rawurlencode() function
To simplify just full the list of the variable $change_to and $to_change
<?php
// Just full the array list to make replacement complete
// In this space will change to _, à to just a
$to_change = [
' ', 'à', 'à', 'â','é', 'è', 'ê', 'ç', 'ù', 'ô', 'ö' // and so on
];
$change_to = [
'_', 'a', 'a', 'a', 'e', 'e', 'e','c', 'u', 'o', 'o' // and so on
];
$texts = 'This is my slug in êlàb élaboré par';
$page_id = str_replace($to_change, $change_to, $texts);

Categories