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?

 

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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;
}

?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.