Jump to content

[SOLVED] replace preg_replace with another function like str_replace


honeyphp

Recommended Posts

I used preg_replace 48 times in my program and it works slowly. I want to replace preg_replace with str_replace.but it doesn't work ,because str_replace can not accept regular expression just string or array.

 

preg_replace:

 

$name= "12e%1223%?!";

 

$name1= preg_replace('/[^a-z0-9\-_]+/i', '', $name);

 

echo $name1;

 

 

str_replace:

 

$name= "12e%1223%?!";

echo "<br>";

$name3= str_replace('/[^a-z0-9\-_]+/i', "", $name);

 

echo $name3;

 

my questions are:

 

1.is there possibility to replace preg_replace with srt_replace?

2.if not ,is there another function that i can use?

3.is there a function that i can conver characters to string?

 

 

 

My server is down so I can't test it or find out if it's faster the using preg_replace(). But try it:

 

<?php
function only_alpha_num($str)
{
$valid_chars = range(65,90) + range(97,122) + range(48,57); //A-Z + a-z + 0-9

$len = strlen($str);
for($i=0, $new_str = ""; $i< $len; $i++)
	$new_str .= (in_array(ord($str[$i]), $valid_chars)) ? $str[$i] : '';
return $new_str;
}
?>

 

Orio.

your code seems perfect (thank you very much )but it doesn't work ,because the + between arrays doesn't work do you know how can ik combine the arrays? range(65,90)+range(97,122)....

<?php
function only_alpha_num($str)
{
$valid_chars = range(65,90) + range(97,122) + range(48,57); //A-Z + a-z + 0-9

$len = strlen($str);
for($i=0, $new_str = ""; $i< $len; $i++)
	$new_str .= (in_array(ord($str[$i]), $valid_chars)) ? $str[$i] : '';
return $new_str;
}

?>

Yep cx323 is right.. It's a place for array_merge() and not the "+" operator since only array_merge() appends the values of arrays that use numeric keys and doesn't overwrite.

 

The line should be:

$valid_chars = array_merge(range(65,90) , range(97,122) , range(48,57));

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.