php replace

Discussion in 'PHP' started by Egnited, Nov 9, 2009.

  1. #1
    One of the fields that my site's database uses is a price range field... some are "$1 to $10", others are "$10 to $20" or "$20 to $30", etc. I want to replace these with $, $$, and $$$ respectively.

    So, if the field says "$10 to $20", I want "$$" displayed instead, etc..

    Can someone please tell me the code for this?
     
    Egnited, Nov 9, 2009 IP
  2. new2seoo

    new2seoo Peon

    Messages:
    143
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You want to update this in database or just while displaying you want to show $,$$,$$$ ?

    if you want to do it in database then you can use mysql
    
    update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);
    
    PHP:


     
    new2seoo, Nov 9, 2009 IP
    Egnited likes this.
  3. ProxyKing

    ProxyKing Peon

    Messages:
    268
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3

    No guarantees this will work, but here you go:

    
    <?php
    $host = 'localhost';
    $dbuser = 'databaseuser'; 
    $dbpass = 'databasepassword';
    $dbname = 'databasename';
    $connection = mysql_connect("$host", "$dbuser", "$dbpass") or die();
    mysql_select_db("$dbname") or die("Database connection error.");
    
     $result = mysql_query("SELECT id as priceid, price as price FROM forsale ORDER BY id ASC");
    while($foundinfo = mysql_fetch_assoc($result))
    {
    	$id = $foundinfo['priceid'];
    	$price = $foundinfo['price'];
    $realprice = substring($price,1);
    $digits = strlen($realprice);
    for ($i = 0; $i < $digits; $i++){
    $finalvalue = $finalvalue."$";
    }
    $finalvalue = $finalvalue.$realprice;
    mysql_query("UPDATE forsale SET price='$finalvalue' WHERE id='$id'");
    }
    ?>
    
    Code (markup):
    Note: You will ahve to update the query
    I am assuming you have a primary key named ID, and that your cost is named price and the table is forsale

    Something like that should do!
     
    ProxyKing, Nov 9, 2009 IP
    Egnited likes this.
  4. Egnited

    Egnited Well-Known Member

    Messages:
    792
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    110
    #4
    Can't I just do a simple str_replace function? One for replacing "$1 to $10" with "$", one for replacing "$10 to $20" with "$$" and one for replacing "$20 to $30" with "$$$"?

    That's what I was thinking anyways....

    Thanks for both answers so far!
     
    Egnited, Nov 9, 2009 IP
  5. ProxyKing

    ProxyKing Peon

    Messages:
    268
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #5
    $origonalstring = strreplace($origonalstring,"$1 to $10","$1 to $$10");
     
    ProxyKing, Nov 9, 2009 IP