2011-08-26 71 views
1

我的想法是,除去特殊字符和HTML代碼和替換空格,以破折號 讓我們做它一步一步如何使用破折號代替空格

$text = "Hello world)<b> (*&^%$#@! it's me: and; love you.<p>"; 

現在我需要的輸出成爲Hello-world-its-me-and-love-you 我已經厭倦了這樣的代碼去除特殊字符和HTML代碼

$array = array(); 
$array[0] = "/<.+?>/"; 
$array[1] = "/[^a-zA-Z0-9 ]/"; 

$textout= preg_replace($array,"",$text); 

現在的輸出會是這樣Hello world its me and love you 那麼有沒有什麼辦法可以修改這個合作德,使文本輸出和我一樣需要Hello-world-its-me-and-love-you

確切變得〜謝謝

回答

2

您可能更適合使用strip_tags來爲您擺脫html標籤,然後使用正則表達式來刪除所有非字母數字(或非空格)字符。然後,您可以使用str_replace將空格簡單地轉換爲連字符。注意我還添加了一行將多個空格摺疊到一個空格,因爲這是您在示例中所做的。否則,您將獲得world--its-me而不是world-its-me

<?php  
    $text = "Hello world)<b> (*&^%$#@! it's me: and; love you.<p>"; 
    $text = strip_tags($text); 
    $text = preg_replace('/[^a-zA-Z0-9 ]/', '', $text); 

    //this is if you want to collapse multiple spaces to one 
    $text = str_replace (' ', ' ', $text); 

    $text = str_replace (' ', '-', $text); 
?> 
1

您可以只添加

$textout = str_replace(' ', '-', $textout); 

你的最後一行後hypens更換空間。

相關問題