2011-03-10 33 views
1

我需要一個正則表達式來從twitter名稱中刪除#。PHP刪除#使用preg

嘗試這樣:

$name = '#mytwitter'; 
$str = preg_replace('/\#/', ' ', $name); 

當然,這是一個簡單的解決,但谷歌並沒有幫助。謝謝!

回答

6

你並不需要使用preg_replace,只需使用str_replace

str_replace('#','',$name); 
+0

謝謝,快速編輯後解決。 – BobFlemming

2

你爲什麼要逃跑#

$name = '#mytwitter'; 
$str = preg_replace('/#/', ' ', $name); 

編輯:你原來的代碼不工作了。請注意0​​返回替換的字符串,但不會更改原始。 $str的值是「mytwitter」。

+0

'preg_replace'比'str_replace'慢得多,不需要在這裏使用 – JamesHalsall

+0

@Jaitsu:當然,但是在修改和重寫代碼之間總是有一個折衷。原始海報最能從中受益的並不明顯。 – Tim

1

你不需要逃避#

$str = preg_replace('/#/', '', $name); 

但是,對於簡單的字符刪除,您最好使用str_replace()。這些情況會更快。

$str = str_replace('#', '', $name); 
1

我會建議使用strtok這一點,因爲它是更好的性能。只要使用它像這樣:

$str = strtok('#mytwitter', '#'); 

這裏有一些基準測試我只是跑(50000次迭代):

strreplace execution time: 0.068472146987915 seconds 
preg_replace execution time: 0.12657809257507 seconds 
strtok execution time: 0.043070077896118 seconds 

我曾經基準的腳本(從Beautiful way to remove GET-variables with PHP?拍攝):

<?php 

$number_of_tests = 50000; 

// str_replace 
$mtime = microtime(); 
$mtime = explode(" ",$mtime); 
$mtime = $mtime[1] + $mtime[0]; 
$starttime = $mtime; 

for($i = 0; $i < $number_of_tests; $i++){ 
    $str = "#mytwitter"; 
    $str = str_replace('#' , '', $str); 
} 
$mtime = microtime(); 
$mtime = explode(" ",$mtime); 
$mtime = $mtime[1] + $mtime[0]; 
$endtime = $mtime; 
$totaltime = ($endtime - $starttime); 
echo "strreplace execution time: ".$totaltime." seconds; <br />"; 

// preg_replace 
$mtime = microtime(); 
$mtime = explode(" ",$mtime); 
$mtime = $mtime[1] + $mtime[0]; 
$starttime = $mtime; 

for($i = 0; $i < $number_of_tests; $i++){ 
    $str = "#mytwitter"; 
    $str = preg_replace('/#/', ' ', $str); 
} 
$mtime = microtime(); 
$mtime = explode(" ",$mtime); 
$mtime = $mtime[1] + $mtime[0]; 
$endtime = $mtime; 
$totaltime = ($endtime - $starttime); 
echo "preg_replace execution time: ".$totaltime." seconds; <br />"; 

// strtok 
$mtime = microtime(); 
$mtime = explode(" ",$mtime); 
$mtime = $mtime[1] + $mtime[0]; 
$starttime = $mtime; 

for($i = 0; $i < $number_of_tests; $i++){ 
    $str = "#mytwitter"; 
    $str = strtok($str, "#"); 
} 
$mtime = microtime(); 
$mtime = explode(" ",$mtime); 
$mtime = $mtime[1] + $mtime[0]; 
$endtime = $mtime; 
$totaltime = ($endtime - $starttime); 
echo "strtok execution time: ".$totaltime." seconds; <br />"; 

    [1]: http://php.net/strtok 
+0

感謝您的支持,我們將對此進行調查,總是得心應手才能加快速度! – BobFlemming