2010-09-24 55 views
1

我如何去掉所有的空白區域和 preg_replace:如何去掉所有空白區域並 ?

我有這個作爲一個包裝我創建了一個輸入,

[b]       bold       [/b]

所以打開文本加粗之前,我想去掉所有的空格和& NBSP,並把它變成[b]bold[/b]

$this->content = preg_replace("/\[(.*?)\]\s\s+(.*?)\s\s+\[\/(.*?)\]/", 
       "[$1]$2[/$3]", 
       $this->content); 

但它不工作!你能幫忙嗎?

+0

問題很簡單,PHP不能識別'' 作爲一個空白字符,僅僅是因爲它是INFACT只是一個6串字符。如果你想使用regexps,你需要告訴php明確地匹配' '。 – poke 2010-09-24 16:52:50

+0

你在哪裏得到這些' '?可能不會添加它? – 2010-09-24 17:05:04

回答

3

字符串我發現了另一個解決方案

$this->content = preg_replace("/\[(.*?)\]\s*(.*?)\s*\[\/(.*?)\]/", "[$1]$2[/$3]", html_entity_decode($this->content)); 
6

不需要基於正則表達式的解決方案。你可以簡單地使用str_replace爲:

$input = "[b]       bold       [/b]"; 
$input = str_replace(array(' ',' '),'',$input); 
echo trim($input); // prints [b]bold[/b] 
+2

這將刪除'[b]'之外的空白。但我不知道這是否是預期的行爲。 – NikiC 2010-09-24 16:53:58

+0

看着他的樣本輸入/輸出看起來像那是他想要的。 – codaddict 2010-09-24 16:54:51

+0

除了樣本不在標籤外顯示文本外。 – poke 2010-09-24 16:58:35

1

你可以只用空字符串,例如更換空間

preg_replace("/(?:\s| )+/", "", $this->content, -1) 

-1導致替換命中匹配的每個實例。

1
$this->content = preg_replace(
    '~\[(.*?)](?:\s| )*(.*?)(?:\s| )*\[/\\1]/', 
    '[$1]$2[/$1]', 
    $this->content 
); 
+0

這也不管用。原始問題沒有顯示OP想要刪除的' '字符。此外,您的解決方案根本無法工作,因爲方括號不會被轉義,並且您的所有分組也無濟於事。 – poke 2010-09-24 16:54:30

+0

@poke:我不明白你想說什麼。結束方括號']'不需要轉義。我所做的只是採用OP的正則表達式,刪除不必要的部分並添加「 '的識別。 – NikiC 2010-09-24 17:12:03

+0

@nikic:哼?你是否改變了你的答案? – poke 2010-09-24 17:14:40

0

爲了讓您使用正則表達式,以及一個完整的解決方案:

$this->content = preg_replace('/\[([a-z]+)\](?: |\s)*(.*?)(?: |\s)*\[\/([a-z]+)\]/', '[$1]$2[/$3]', $this->content); 

但在這種情況下,你倒是應該結合空白移除,並設置高亮改造,以確保標籤是正確的:

$this->content = preg_replace('/\[b\](?:&nbsp;|\s)*(.*?)(?:&nbsp;|\s)*\[\/b]/', '<b>$2</b>', $this->content); 
+0

非常感謝你!這就是我要的!謝謝! :-)))) – laukok 2010-09-24 17:52:44

0

,將工作的另一種方法是:

$this->content = trim(str_replace('&nbsp;','',$this->content)); 

PHP手冊鏈接:

裝飾()http://us.php.net/trim

*注:這是假設$這個 - >內容只包含張貼OP

1

有點晚回答,但希望可以幫助別人。從html中提取內容時最重要的是在php中使用utf8_decode()。然後所有其他的字符串操作變得輕而易舉。即使是外來字符也可以直接從瀏覽器中將粘貼字符複製到php代碼中。

以下函數用空字符替換&nbsp;。然後使用preg_replace()將所有空格替換爲空字符。

function clean($str) 
{  
    $str = utf8_decode($str); 
    $str = str_replace("&nbsp;", "", $str); 
    $str = preg_replace("/\s+/", "", $str); 
    return $str; 
} 

$html = "[b] &nbsp; &nbsp; &nbsp; bold &nbsp; &nbsp; &nbsp; [/b]"; 
$output = clean($html); 
echo $output; 

並[b]粗體[/ B]