PHP bir dize sonunda bir sonek eklemek nasıl

6 Cevap

Ben veritabanına girilmeden önce kullanıcı tarafından verilen bütün dizeler sonunda. Html eki eklemek çalışıyorum. İşte benim kod kadar bulunuyor:

strtolower(str_replace(" ", "_", $postTitle));

Yukarıda, kullanıcı bunu yapmaya çalışıyorum yazının başlığını alır o harfe dönüşür, çizgi ile tüm beyaz boşluk yerini ve bir veritabanı sütun denilen post_url girilmesine hazır hale getirir.

Ben sadece bir şey daha yapmak gerekir ve bu her sonrası url sonunda bir. Html eklemek için bulunuyor. Bunu yapmak için fonksiyonu nedir?

6 Cevap

belki de ben senin soruyu olsun, ama ne bu konuda değil:

strtolower(str_replace(" ", "_", $postTitle)).'.html';

Gerçekten simiple cevap:

$url_string = strtolower(str_replace(" ", "_", $postTitle)).'html';

ancak, güvenliği ve url için kötü karakterler kaçan dikkate almak gerekir.

Eğer iki sorunları çözmek yaparak çıkarın ve olmayan alfa-sayısal karakter gerekir

  1. Olası SQL injection

  2. geçersiz URL'ler

ör

// remove all bad chars from string e.g. commas, single quotes etc
$url_string = preg_replace(“/[^a-zA-Z0-9\s]/”, “”, $postTitle);
// replace spaces with underscore and make all lowercase 
$url_string = strtolower(str_replace(" ", "_", $url_string));
// add .html to end of string.
$url_string = $url_string.'html';
$postTitle = strtolower(str_replace(" ", "_", $postTitle));    
$postTitle .= '.html';

.= Birleştirme ve PHP atama operatörüdür. Bu $ postTitle sonuna kadar üzerinde string '. Html' eklemek ve daha sonra eşit $ postTitle değerini ayarlar. Sadece böyle daha yapabilirsiniz birlikte iki dizeleri borular ile arka arkaya isterseniz:

$string3 = $string1.$string2;
$newName = strtolower(str_replace(" ", "_", $postTitle)) . '.html';

Sadece aslında boşluk değil, beyaz alan her türlü alıcı konum olsa, "beyaz boşluk" söz. Eğer belirli bir sorun hakkında ne söylediğim dayanarak, bu yeterli muhtemelen, ama dikkate vermek emin olun sekme ("\ t") ve / veya newlines & olsun linefeeds ("\ n", "\ r") de mevcut olabilir.

whould:

strtolower(str_replace(" ", "_", $postTitle)).".html";

hile yapmak?

Bu benim görüşüme göre daha yumuşak bir çözümdür:

function handle_create($string) {
  $healthy = array(' ', 'å', 'ä', 'ö');
  $yummy = array('-', 'a', 'a', 'o');
  $string = str_replace( $healthy, $yummy, mb_strtolower( $string, 'UTF-8' ) );
  $string = preg_replace('/-{1,}/', '-', $string );
  return preg_replace('/[^a-z0-9\-\/]/i', '', $string) ;
}

$title = 'Lörem ipsum dålor sit amet - consectetur adipiscing elit.';
echo handle_create( $title );

Neden olur

lorem-ipsum-dalor-otur-amet-consectetur-adipiscing-elit