help with preg_replace

Discussion in 'PHP' started by Dirty-Rockstar, Jul 18, 2008.

  1. #1
    im trying to insert a html form post into table A, and add a field into table b with that information. the form information has a space, but i want to change that space into an _ for the field entry and i cant seem to get preg_replace to work. :/ help?

    
    $name=clean($_POST[name]);
    $info=clean($_POST[info]);
    include('tablestart.php'); //irrelevant 
    
    //print "Name: $name<br /> Info: $info"; <---old debug
    
    
    $sql="INSERT INTO items_static (name,info)VALUES('$name','$info')" or die(mysql_error());
    $query=mysql_query($sql) or die(mysql_error());
    
    //^^ works fine
    
    $name=preg_replace(" ","_",$name);
    
    $sql="ALTER TABLE `items` ADD `$name` VARCHAR( 25 ) NOT NULL DEFAULT '0'";
    $query=mysql_query($sql) or die(mysql_error());
    
    PHP:

    Im on the fail train for sure with this. any help is appreciated
     
    Dirty-Rockstar, Jul 18, 2008 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Use the preg_* functions ONLY for regular expressions. They're too slow for simple replacements as this.

    Use str_replace(): www.php.net/str_replace
     
    nico_swd, Jul 18, 2008 IP
  3. php-lover

    php-lover Active Member

    Messages:
    261
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    58
    #3
    $name = 'php lover';
    $name=preg_replace('/\s/','_',$name);
    echo $name;
    
    PHP:
    :)
     
    php-lover, Jul 18, 2008 IP
    Dirty-Rockstar likes this.
  4. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4

    I tried to use it this way and just couldnt figure out the function right. But i just woke up so i might try it later. thanks.


    worked like a charm thanks = )
     
    Dirty-Rockstar, Jul 18, 2008 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    str_replace() and preg_replace() take the same order and number of arguments. So all you have to do is take your code and replace the word preg_replace with str_replace.
     
    nico_swd, Jul 18, 2008 IP