SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: ereg_replace problem
-
Jun 13, 2007, 18:32 #1
- Join Date
- Mar 2007
- Location
- The Netherlands
- Posts
- 61
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
ereg_replace problem
Hi i got this code:
PHP Code:function removedata2($str, $a=false)
{
$str = ereg_replace("[^A-Za-z0-9]", "-", $str);
$str = str_replace("'","", $str);
$str = str_replace("&","&", $str);
$str = strip_tags($str, '');
if ($a==true && strlen($str)>=1000000){
$str=substr($str, 0, 1000000)."..";
}
return $str;
}
But my code got weird bug with ereg_replace.
That it makes: hello---my-name---is-
So sometimes it does -- and sometimes one -
Looks like he replaces every char expect AZ az 09
Is there way to do this nicer? And cleaner.
So i get nice url title with single - in it?
-
Jun 14, 2007, 01:35 #2
- Join Date
- Aug 2004
- Location
- Manchester UK
- Posts
- 13,807
- Mentioned
- 158 Post(s)
- Tagged
- 3 Thread(s)
Isnt this line:
PHP Code:// removed carat ^ from regex
$str = ereg_replace("[A-Za-z0-9]", "-", $str);
Code:-----------------
What are you trying to do Gerlof?Mike Swiffin - Community Team Advisor
Only a woman can read between the lines of a one word answer.....
-
Jun 14, 2007, 01:39 #3
If you have multiple non-alphanumeric characters after each other, then you will get multiple hyphens instead. If you think that ereg_replace is behaving irregularly then please post some examples of $str with the corresponding return values of removedata2.
By the way, the two calls to str_replace and the one to strip_tags are superfluous because after ereg_replace there will be no more special characters in your string which could be replaced or stripped.
edit: I only see this now:
Originally Posted by Gerlof
Never ascribe to malice,
that which can be explained by incompetence.
Your code should not look unmaintainable, just be that way.
-
Jun 14, 2007, 02:52 #4Code php:
function removedata2($str, $a = false) { $str = preg_replace(array('/[^a-z0-9]+/i', '/-{2,}/'), '-', $str); if ($a && strlen($str) >= 1000000) { $str = substr($str, 0, 1000000) . '..'; } return $str; }
preg_* uses Perl-compatible syntax using the PCRE functions which is more widely supported then POSIX Extended at least of what I seen.
Edit:
It has come to me attention that the regex function can be simplified down to:
Code php:function removedata2($str, $a = false) { $str = preg_replace('/[^a-z0-9]+/i', '-', $str); if ($a && strlen($str) >= 1000000) { $str = substr($str, 0, 1000000) . '..'; } return $str; }
No need for the second regex '/-{2,}/'
Bookmarks