I' am creating a slug on the fly. When I review the database my slug row looks like this
laal-salaam---2002
What actually I don't want is duplicate hyphen between the words.
$crawl_slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $crawl_name);
$crawl_slug = strtolower($crawl_slug);
Thats the PHP code that handles in making the slug from the name on the fly.
The end result should be
laal-salaam-2002
Is there any other way I can achieve this issue. Thanks!
This is a Simple Function I use for years.
<?php
function to_slug($string)
{
$string = trim($string);
$string1 = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));
return preg_replace("/\-+/i", "-", $string1);
}
$slug = to_slug("laal-salaam---2002");
echo $slug
?>
Related
I've written small framework like code with HMVC architecture using PHP. Below are the sample SEF URLs to access.
http://domain.com/controller_name/method_name/param1/param2
http://domain.com/folder_name/controller_name/method_name/param1/param2
Above are fine and working with the fixed kind of data. But when I tried building a simple CMS, where I've category inside another category and other and so on i.e., multi-level category structure with set of articles inside, I was not able to make use of above URL. I want something like
http://domain.com/category-name/sub-category-name/sub-sub-category-name
http://domain.com/category-name/sub-category-name/article-name
Can anyone help me with snippet to achieve above.
if i did not misunderstand you want to query category by sefurl
firstly you need to convert data name to sefurl
function sefurl($s){
$s=trim($s);
$tr = array('ş','Ş','ı','I','İ','ğ','Ğ','ü','Ü','ö','Ö','Ç','ç','(',')','/',':',',');
$eng = array('s','s','i','i','i','g','g','u','u','o','o','c','c','','','-','-','');
$s = str_replace($tr,$eng,$s);
$s = preg_replace('/&amp;amp;amp;amp;amp;amp;amp;.+?;/', '', $s);
$s = preg_replace('/\s+/', '-', $s);
$s = preg_replace('|-+|', '-', $s);
$s = preg_replace('/#/', '', $s);
$s = str_replace('.', '.', $s);
$s = trim($s, '-');
$s = htmlspecialchars(strip_tags(urldecode(addslashes(stripslashes(stripslashes(trim(htmlspecialchars_decode($s))))))));
return $s;
}
now you can test it
for example my categori name is "this is a test categoriğ"
sefurl($catname);
result is going tobe like "this-is-a-test-categorig"
you can use this for categori id
create a new colon in your DB table like sefurl when you set a new categoriy convert the categori name to sefurl and than set it to sefurl colon
you can query by sefurl of the categori
http://yourdomain.com/categori/this-is-a-categor-/
parse url by "/" and get "this-is-a-categor-" after that query it in your categori table.
I have a slug function that I am using from another tutorial.
public function createSlug($slug) {
// Remove anything but letters, numbers, spaces, hypens
// Remove spaces and duplicate dypens
// Trim the left and right, removing any left over hypens
$lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
$spacesDuplicateHypens = '/[\-\s]+/';
$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));
$slug = preg_replace($spacesDuplicateHypens, '-', $slug);
$slug = trim($slug, '-');
return $slug;
}
It works great. I have two questions.
It gives me 'amp' instead of removing the '&' symbol. Not sure if it should be like that.
For eg.
original url
http://www.mywebsite.com?category_id=1&category_name=hot & dogs
new url using slug function
http://www.mywebsite.com?category_id=1&category_name=hot-amp-dogs
and second, how do I decode it back to the original form so that I can echo it out on the page? It doesn't look right echoing with dashes.
Use "htmlspecialchars_decode". see below modified function:
function createSlug($slug) {
// Remove anything but letters, numbers, spaces, hypens
// Remove spaces and duplicate dypens
// Trim the left and right, removing any left over hypens
$slug = htmlspecialchars_decode($slug);
$lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
$spacesDuplicateHypens = '/[\-\s]+/';
$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));
$slug = preg_replace($spacesDuplicateHypens, '-', $slug);
$slug = trim($slug, '-');
return $slug;
}
For decode, agree with Rakesh Sharma. Use database to manage this.
In my MySQL database I have this table which contains multiple artists. They are placed in a field called formated_name and returns strings like for example Lady Gaga, so far so good. What I want to achieve is that it returns ladygaga so I can use it for my url later on. My whole function looks like this:
public function artistname_get($artist_id)
{
$this->load->database();
$sql = "SELECT formated_name FROM artists WHERE artist_id = '".$artist_id."'";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artist with that name!'), 404);
}
}
So how can I achieve this?
Try out this simple way.
To remove spaces in string.
By using PHP
$string = 'Lady Ga ga';
$value=str_replace(' ','',$string);
echo strtolower($value);
By using MySQL
$sql = "SELECT REPLACE( formated_name, " ", "" ) FROM artists WHERE artist_id = '".$artist_id."'";
Mysql offers string function for this as well if you do not want to do it with php.
ToLower function:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_lower
Replace to replace spaces:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
But you should additionally use something for url_encode and url_decode within php. Otherwise you may experiance problems with artists like "A & B"
Use
str_replace() and `strtolower()`
to remove space and to convert string to lowercase.
PHP version:
$string = strtolower(str_replace(' ', '', $string));
$artist_url = strtolower(str_replace(' ', '', $artist_formatted_name));
$string = strtolower(str_replace(' ', '', $string));
Try this,
SELECT LOWER(REPLACE(formated_name, ' ', '')) AS formated_name
You have to do is Just use mysql functions LOWER and REPLACE together to get rid of space and capital letters
Try Something like this.....
<?php
$string = 'Lady Gaga';
$value=str_replace(' ','',$string);
echo strtolower($value);
?>
If you want to put it in URL you should clear also from special characters etc.
Use this function to convert string into alias.
function toAlias ($string) {
return strtolower (preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', $string)));
}
I am using only slug to identify a page on the website, like: example.tld/view/this-fancy-slug . This is generated from the title automatically with this function:
public static function Normalize($str)
{
$charset = "UTF-8";
$separator = "-";
$str = strtolower(htmlentities($str, ENT_COMPAT, $charset));
$str = preg_replace('/&(.)(acute|cedil|circ|lig|grave|ring|tilde|uml);/', "$1", $str);
$str = preg_replace('/([^a-z0-9]+)/', $separator, html_entity_decode($str, ENT_COMPAT, $charset));
$str = trim($str, $separator);
return $str;
}
This returns a perfect slug... but I need unique slugs. So I've to combine with mysql to check if exists a slug that fits with the created. No problem with that.
The problem is that I want to add a -1 at the final if there is ONE slug. But can be buggy if are added 3 equal slugs so... how can I manage this to go from slug, slug-1, slug-2, slug-3... slug-100, slug-n?
Thank you in advance!
Don't just check if that identical slug is present. Use a regular expression to count all the slugs that follow the pattern /(<base-regex-for-slug>)(-\d+)?/. Because you only allow alphanumerics your base regex above will be the slug itself.
I want to make http://mysite.com/id255/ to http://mysite.com/gora-beach-inn/.
My php looks like:
$result = mysql_query("
SELECT id, header
FROM Article
");
while($data = mysql_fetch_assoc($result)){
mysql_query("
UPDATE Article
SET seo = '".MakeSeo($data['header'])."'
WHERE datum = '".$data['datum']."'
");
}
//Convert: "åäö" to "aao", "space" to "-", "!?" to "nothing", and all to lower case.
function MakeSeo($string)
{
???
}
Please help me with the MakeSoe function.
I use moderewrite, so I just need help to generate the url, so I can save them in my database.
To just answer your requirement ..
here you go ..
function makeSeo($text, $limit=75)
{
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
if(strlen($text) > 70) {
$text = substr($text, 0, 70);
}
if (empty($text))
{
//return 'n-a';
return time();
}
return $text;
}
You can add more filters to clean the url and may be you add some more stuff to get that url a unique.
Note: I am not saying that adding url to the database is the best way. You could achieve the same sort of functionality using other techniques, for example, mod_rewrite.
You would need to use mod_rewrite to achieve this, otherwise the other approach is the 'internal' method done by php, where you would do something similar to:
http://mydomain.com/index.php/category/dogs
the above is just a GET post, and index handles the content loading via includes / mysql etc;
Non regular expression and more flexible solution can be done via 2 arrays. Define all charcters in from and to arrays. Omitted characters will be than replaced by -
This is example of javascript function
function ToSeoFriendly(title) {
title = title.toLowerCase();
var generated = "";
var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñçýčšžřľňäôabcdefghijklmnopqrstuvwxyz1234567890";
var to = "aaaaaeeeeeiiiiooooouuuuncycszrlnaoabcdefghijklmnopqrstuvwxyz1234567890-";
for (var i=0;i<title.length;i++){
generated += to.substr(from.indexOf(title.substr(i,1)),1);
}
return generated;
}