开发者

PHP Remove # using preg

I need a regex to remove the # from a twitter name.

Tried this:

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

Sure this is a simple fix , but 开发者_C百科Google didn't help. Thanks!


You don't need to use preg_replace, just use str_replace:

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


Why are you escaping #?

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

Edit: Your original code does work, too. Note that preg_replace returns the substituted string but doesn't change the original. The value of $str is " mytwitter".


You do not need to escape #.

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

However, for a simple character removal, you are better off using str_replace(). It's faster for those situations.

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


I would recommend using strtok for this, as it's more performant. Just use it like so:

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

Here are some benchmarks i just ran (50000 iterations):

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

The script i used to benchmark is (taken from 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜