Welcome to WebmasterWorld Guest from 54.204.162.36

Forum Moderators: coopster & jatar k

preg replace problem

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

5+ Year Member



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)

5+ Year Member



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)

5+ Year Member



Hello,

Thanks for reply. But it not works :(.

Vineet

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

5+ Year Member



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)

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



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>
 

Featured Threads

Hot Threads This Week

Hot Threads This Month