2015-08-24 146 views
0

我正在開發一個專注於動物的網站。網址​​與我的數據庫中的值Ursus-maritimus相符。從URL中刪除撇號

但我也想在生物體的通用名稱,以顯示此頁面 - 「北極熊」 mysite/life/polar-bear

沒問題,我也充滿了共同的名字,其中包括另一個表

$CommonURL = str_replace('-', ' ', $MyURL); 

[QUERY WHERE CLAUSE] WHERE Name_Common = :CommonURL 

但對於像Grevy’s zebra一個共同的名字:我只是用這樣一個連字符替換這兩個詞之間的空間?我如何修改我的WHERE子句,使其忽略撇號,重音符號等,顯示一個URL,如mysite/life/grevys-zebra

+0

您不必刪除的話,只是編碼\逃脫他們 –

+0

什麼'mysite的/生活/細紋%-27-zebra'? – chris85

+0

Dagon,如果我理解正確,編碼意味着URL看起來像grevy's-zebra。如果我想要一個像grevys-zebra這樣的「乾淨的URL」,我需要轉義’。我怎麼做? –

回答

1

使用str_ireplace

$MyURL="Grevy’s zebra"; 
$CommonURL = str_ireplace("’", "’", $MyURL); 
echo $CommonURL = htmlentities($CommonURL); 
//this would echo Grevy’s zebra 
+0

Thx;我甚至不熟悉str_ireplace。它還不適合我,但我可能只需要玩它。我希望URL grevys-zebra匹配數據庫值'Grevy ’ s斑馬' –

+0

現在看。是你想要的:) – aimme

+0

對不起,它不適合我。但就像我說的,我可能只需要再玩一點。 –

1

好吧,如果我理解正確的,你想去掉一切自然字符;如果是這樣的話,那麼你可以這樣做:(代碼有很好的註釋:))

<?php 
echo '<pre>'; 

$names = array(
    'polar bear', 
    'Grevy\'s zebra', 
    'wet \'n wild!', 
    'Nature: Alaska', 
    '#myName', 
    'dog % cat', 
); 
echo "names:\n"; 
print_r($names); 

// "urlencode"ing them! 
$names_encoded = array(); 
foreach($names as $name) 
    $names_encoded[] = urlencode($name); 

echo "\n\nnames_encoded:\n"; 
print_r($names_encoded); 

$out = array(); 
foreach($names_encoded as $name_encoded) 
    $out[] = preg_replace(
     array('#%[0-9a-fA-F]{2}#', '#\+#'), // finds the patterns like '%HH' (H represents an Hexadecimal digit), and '+'; the latter representing the spaces 
     array('', '-'), // replace the '%HH' matches with nothing ('') and the '+' matches with '-' 
     $name_encoded 
    ); 

echo "\n\nout:\n"; 
print_r($out); 
?> 

輸出的摘錄是:

out: 
Array 
(
    [0] => polar-bear 
    [1] => Grevys-zebra 
    [2] => wet-n-wild 
    [3] => Nature-Alaska 
    [4] => myName 
    [5] => dog--cat 
) 
1

如果要替換撇號和其他帶連字符的標點符號,您可以使用這三行代碼來創建乾淨的URL段落。我多年來一直使用類似的代碼片段,而且非常堅固。一個警告是,第三行是用於英語slu;的;如果需要,您需要將任何非英文字符添加到可接受的字符列表中。

// clean, normalize, and lowercase the string 
$slug = strtolower(trim(strip_tags(stripslashes($slug)))); 

// replace any whitespace (tabs or even multiple spaces) with hyphens 
// this is MUCH more robust than just using str_replace('-', ' ', $MyURL); 
$slug = preg_replace('/\s+/', '-', $slug); 

// convert punctuation or other non-alphanumeric characters to hyphens 
$slug = preg_replace('/[^a-z0-9-]/', '-', $slug);