PHP使用preg删除#

时间:2011-03-10 17:17:48

标签: php regex

我需要一个正则表达式从Twitter名称中删除#。

试过这个:

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

当然这是一个简单的解决方案,但谷歌没有帮助。谢谢!

4 个答案:

答案 0 :(得分:6)

您无需使用preg_replace,只需使用str_replace

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

答案 1 :(得分:2)

你为什么逃脱#

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

修改:您的原始代码也可以正常运行。请注意preg_replace返回替换字符串但不更改原始字符串。 $str的值是“mytwitter”。

答案 2 :(得分:1)

您无需转义#

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

但是,对于简单的字符删除,最好使用str_replace()。这种情况更快。

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

答案 3 :(得分: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