Welcome to WebmasterWorld Guest from 50.17.117.221

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

preg replace problem

     
9:53 am on Aug 26, 2006 (gmt 0)

Junior Member

10+ Year Member

joined:Sept 3, 2005
posts:131
votes: 0


Hello,

I want to replace all character other then alphanumeric to "-", to get this output i wrote this expression but it not works, please check it.

preg_replace([^a-zA-Z0-9],"-",$string);

Please help.

Vineet

11:55 am on Aug 26, 2006 (gmt 0)

Preferred Member

10+ Year Member

joined:Aug 6, 2005
posts:575
votes: 0


You may need to add a $ to the pattern, so that it knows to stop:


preg_replace([^a-zA-Z0-9$],"-",$string);
12:40 pm on Aug 26, 2006 (gmt 0)

Junior Member

10+ Year Member

joined:Sept 3, 2005
posts:131
votes: 0


Hello,

Thanks for reply. But it not works :(.

Vineet

12:53 pm on Aug 26, 2006 (gmt 0)

Preferred Member

10+ Year Member

joined:Aug 6, 2005
posts:575
votes: 0


Try this (not tested, but similar to something I use):


preg_replace("^([a-zA-Z0-9])$","-",$string);
1:49 pm on Aug 26, 2006 (gmt 0)

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12533
votes: 0


compose, your original pattern would have worked but you need to supply delimiters [php.net]. Also remember that the original string remains the same, you need to assign the replaced value to either the original variable or a new variable:
<pre> 
<?php
$string = 'abcABC123-@#4abcABC123';
print "$string\n";
$updatedString = preg_replace("/[^a-zA-Z0-9]/","-",$string);
print "$string\n";
print "$updatedString\n";
?>
</pre>