2014-12-13 33 views
0

我使用的preg_replace刪除從字符串不需要的內容,這是工作,但它留下2個空格,所以......的preg_replace被留下兩個空格

$content = '[content I want deleted including square brackets] this would be content that I want left!'; 

$result = preg_replace('`\[[^\]]*\]\`','',$content); 

    echo $result; 

這上面產生以下(」 __「代表兩個空格)

__this會的內容,我想離開!

結果應該是...

這將是我想要的內容!

沒有前面的兩個空間,可有人告訴我在哪裏,我錯了。謝謝。

+2

你的正則表達式不會查找'\ s'空格。也可以使用'trim()'。並且爲什麼最後的反撥逃脫了? – mario 2014-12-13 00:32:29

+0

['trim()'](http://php.net/trim)並完成。不要害怕使用多個函數來完成一項任務 – 2014-12-13 00:37:12

+0

我對php有點新,雖然大部分時間我都可以閱讀代碼並理解它,但這仍然是在逃避我。它讓我想起了htaccess。非常感謝你的幫助,我很感激。 – Alex49 2014-12-13 16:24:12

回答

0

不知道你的代碼,但我測試了這個好,工作好

$content = '[content __I want deleted including square brackets] this would be content that I want left!'; 

$result = preg_replace('#\[([^\]]*)\]#is','',$content); 

    echo $result; 

(我用「是」,因爲我總是忘記圖案修飾的含義,並且它們很管用,如果你不知道檢查http://php-regex.blogspot.it/

+0

這很酷,非常感謝。 – Alex49 2014-12-13 16:25:38

0

就在正則表達式的末尾添加可選空間:

$content = '[content I want deleted including square brackets] this would be content that I want left!'; 
$result = preg_replace('`\[[^\]]*\]\s*`', '', $content); 
echo $result; 

這給:

this would be content that I want left! 

沒有在開始時的空間。