PHP url uyumlu moduna başlık dönüştürmek için en iyi yolu?

5 Cevap php
http://domain.name/1-As Low As 10% Downpayment, Free Golf Membership!!!

Yukarıdaki url rapor 400 bad request, olacak

ne kadar kullanıcı dostu good isteğine böyle başlık dönüştürmek için?

5 Cevap

Bunun yerine bir "sümüklü böcek" kullanmak isteyebilirsiniz. Aksine URL olarak birebir unvanını kullanmak yerine, strtolower() and replace all non-alphanumeric characters with hyphens, then remove duplicate hyphens. If you feel like extra credit, you can strip out stopwords, çok.

Yani "10% Ön Ödeme, Ücretsiz Golf Üyeliği As 1-As Low!" olur:

as-low-as-10-downpayment-free-gold-membership

Böyle bir şey:

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;
}

Muhtemelen uzun regexplerde ile kısaltabilir ama olduğu gibi-oldukça basittir. Bonus başlık maç için veritabanı üzerinde bir sorgu çalıştırmadan önce sorgu parametre doğrulamak için aynı işlevi kullanabilirsiniz, böylece birisi veritabanına aptalca şeyler sopa olamaz olmasıdır.

You can use urlencode or rawurlencode... for example Wikipedia do that. See this link: http://en.wikipedia.org/wiki/Ichigo_100%25

Bu php kodlama var% =% 25 için

Burada ilk cevap bakın 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

Ben sadece yararlı bir sülük fonksiyonu olan bir yüreğin oluşturun:

https://gist.github.com/ninjagab/11244087

Sen dost url seo başlık dönüştürmek için kullanabilirsiniz.

<?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