• (cs)

    Let's see...

    • A whole function to replace str_replace
    • Instead of short circuiting up front, prepend A, then process and then strip
    • Calling strpos twice each time through the loop instead of saving the value
    • Not checking if whatever character matches is the last char (not sure what substr does if start index > string len)

    It must be Monday...

  • EatenByAGrue (unregistered)

    The signal that this was a WTF is a file named "everything.inc", because any code named "everything" is:

    1. Misnamed.
    2. Full of foolishly reimplemented library calls like this one.
    3. Not at all modular.
  • (cs)

    What happens when I write "$1,000.00"?

  • Janis Petke (unregistered)

    TRWTF: fixString() doesn't even remove the '$' characters.

  • (cs)
    "Great!" Jared replied, clenching my teeth.

    He was clenching your teeth? That sounds uncomfortable.

  • Josh (unregistered) in reply to SlyEcho
    SlyEcho:
    What happens when I write "$1,000.00"?

    Yeah. I got burned by something like that once.

    The listings for some computers in a point-of-sale system ended up with prices of $1.

    (It was script to convert stuff to CSV format. facepalm)

  • (cs) in reply to SlyEcho
    SlyEcho:
    What happens when I write "$1,000.00"?

    That should be fine. PHP doesn't give a crap about types so it will assume 1,000.00 is an int after you strip the $.

    Janis Petke:
    TRWTF: fixString() doesn't even remove the '$' characters.

    I think you're supposed to pass an array('$') to the function.

    At any rate definitely putting php code in a .inc file is the best way to store server side code.

  • (cs) in reply to EatenByAGrue
    EatenByAGrue:
    The signal that this was a WTF is a file named "everything.inc", because any code named "everything" is: 1. Misnamed. 2. Full of foolishly reimplemented library calls like this one. 3. Not at all modular.

    I wish I had an "everything.inc". I'd never have to write new code again!

  • Nicd (unregistered)

    The real WTF are the double quotes in $cleanedPrice = str_replace(array('$'), "", $price);

  • planck (unregistered)

    The real WTF is that the solution Jared wrote is so... specific.

    $cleanedPrice = preg_replace("/[^0-9.]/", "", $price);

  • (cs)

    HA HA ! TRWTF IS PHP.

  • \ (unregistered)

    That is why he is in charge and you were aren't -

    You would have taken 1 minute.

    He took 10.

    You get paid for 1 minute.

    He gets paid for for 10.

  • (cs)

    include "cluestick.inc"

    fixBrian(3); // 3 strokes should be enough.

  • jmucchiello (unregistered)

    I'd like to know what other gems can be found in everything.inc.

  • Zap Brannigan (unregistered) in reply to planck
    planck:
    The real WTF is that the solution Jared wrote is so... specific.

    $cleanedPrice = preg_replace("/[^0-9.]/", "", $price);

    Goody, another regex thread. Your solution looks like it will work. I'm sure there will be other examples.

  • cod3_complete (unregistered)

    I've seen this kind of WTF coding far too much in my time and it just has to stop. Reimplementing an existing API is one of the worst damn things anyone can do. Unfortunately, the PHP api is inconsistent in both naming conventions and use of underscores so it can be easy to get lost when the language looks like spaghetti and is poorly designed.

  • Simetrical (unregistered) in reply to akatherder
    akatherder:
    That should be fine. PHP doesn't give a crap about types so it will assume 1,000.00 is an int after you strip the $.
    PHP will assume *anything* is an int. The problem is getting it to pick the *right* int:

    $ php -r "var_dump( (int)'1,000.00' );" int(1)

    PHP doesn't understand commas when casting strings to ints.

  • (cs) in reply to Simetrical

    In some parts of the world, $1,000 means what you'd type as "$1.000". So there is no way for PHP to really understand commas and dots that easily.

  • (cs) in reply to cod3_complete
    cod3_complete:
    Unfortunately, the PHP api is inconsistent in both naming conventions and use of underscores so it can be easy to get lost when the language looks like spaghetti and is poorly designed.

    Wait, are you implying that PHP was actually designed? Because it sure looks like a few random pieces of code got mixed together by chance and then started to evolve

  • Matt (unregistered) in reply to cod3_complete
    cod3_complete:
    I've seen this kind of WTF coding far too much in my time and it just has to stop. Reimplementing an existing API is one of the worst damn things anyone can do. Unfortunately, the PHP api is inconsistent in both naming conventions and use of underscores so it can be easy to get lost when the language looks like spaghetti and is poorly designed.
    ++

    PHP sucks because:

    1. No types and therefore silent conversions where you don't want them ( === should NOT be nessisary)
    2. No exceptions (in PHP4 which everyone still uses)
    3. No naming conventions for functions
    4. No namespaces
  • (cs) in reply to Zap Brannigan
    Zap Brannigan:
    planck:
    The real WTF is that the solution Jared wrote is so... specific.

    $cleanedPrice = preg_replace("/[^0-9.]/", "", $price);

    Goody, another regex thread. Your solution looks like it will work. I'm sure there will be other examples.
    I can see it now...

    function fixStringf($string, $chars = 0) {
      if (strlen($string) == 1) {
         string=preg_replace("/[^0-9\.]/","",substr($string,0));
      }
      if (strlen($string) == 2) {
         string=preg_replace("/[^0-9\.]/","",substr($string,0,1)) .
                preg_replace("/[^0-9\.]/","",substr($string,1,2));
      }
      ...
    
    }
    
  • I walked the dinosaur (unregistered)

    Do people REALLY not understand the difference between ==false and ===false in php? That's the reason an 'A' is prepended at the start. My god...

  • (cs) in reply to SlyEcho
    SlyEcho:
    What happens when I write "$1,000.00"?
    Jared gets to add commas to his line of code and avoid the "everything" monster again.
  • SNF (unregistered)

    What if 'A' is one of the characters you want to replace?

  • (cs) in reply to Sad Bug Killer
    Sad Bug Killer:
    cod3_complete:
    Unfortunately, the PHP api is inconsistent in both naming conventions and use of underscores so it can be easy to get lost when the language looks like spaghetti and is poorly designed.

    Wait, are you implying that PHP was actually designed? Because it sure looks like a few random pieces of code got mixed together by chance and then started to evolve

    It was a one line of code, preceded by an include that included the file itself. It created a singularity and exploded into what we know as PHP.

  • Erik (unregistered) in reply to Juifeng
    Juifeng:
    In some parts of the world, $1,000 means what you'd type as "$1.000". So there is no way for PHP to really understand commas and dots that easily.

    That's why you include examples of how to write large values in the instructions (such as "1000.00 instead of 1,000.00"). Then, you take the first comma or dot to be the decimal, strip out every other special character, and present the resulting value to the user for confirmation. Eventually, with the program returning a value different from what they expect, the user will figure it out and stop putting extraneous characters in there.

    Of course, that may be putting too much faith in the user's ability to figure things out, but it's better than applying a regex to something that varies by region and just blindly accepting what comes out the other end (especially when we're talking about dollar amounts).

  • (cs) in reply to Juifeng
    Juifeng:
    In some parts of the world, $1,000 means what you'd type as "$1.000". So there is no way for PHP to really understand commas and dots that easily.
    In some programming languages of the world, cultural differences like these are anticipated and taken care of. Of course, casting a string to an int should never be allowed, but if it was, the culture of the computer it runs off could be assumed (as long as there are ways to do it which lets you specify otherwise)
  • (cs) in reply to Sad Bug Killer
    Sad Bug Killer:

    Wait, are you implying that PHP was actually designed? Because it sure looks like a few random pieces of code got mixed together by chance and then started to evolve

    Dang namit, is that where my genetic algorithms program ended up?

  • (cs) in reply to Nicd
    Nicd:
    The real WTF are the double quotes in $cleanedPrice = str_replace(array('$'), "", $price);

    Not really. Single or double quotes would both do just fine here. You'd be hard pressed to notice a discernible performance hit from the empty string being parsed by the zend engine.

    If the double quotes were around the dollar sign, THEN you'd have a wtf, but a noticeable one.

  • (cs) in reply to Matt
    Matt:
    cod3_complete:
    I've seen this kind of WTF coding far too much in my time and it just has to stop. Reimplementing an existing API is one of the worst damn things anyone can do. Unfortunately, the PHP api is inconsistent in both naming conventions and use of underscores so it can be easy to get lost when the language looks like spaghetti and is poorly designed.
    ++

    PHP sucks because:

    1. No types and therefore silent conversions where you don't want them ( === should NOT be nessisary)
    2. No exceptions (in PHP4 which everyone still uses)
    3. No naming conventions for functions
    4. No namespaces

    No naming conventions? Thats a snobby nit to pick.

    The typing issue is pretty vague too; php does suck for the whole weak/dynamic typing thing, but languages like Python also have dynamic typing (though not weak typing), and it adds a lot to usability over pissy static/strongly typed languages like java.

    Finally, php4 is now officially unsupported, so it's not entirely fair to say that "everyone" is using it. I don't use php all that much, and but I've been using 5 for a good while.

    Php is fine for what it does. Sure it can produce crap code, but it's not a requirement. I'll agree with you on the namespace thing though; that's a royal p.i.t.a.

  • (cs) in reply to snoofle
    snoofle:
    Let's see...
    • A whole function to replace str_replace
    • Instead of short circuiting up front, prepend A, then process and then strip
    • Calling strpos twice each time through the loop instead of saving the value
    • Not checking if whatever character matches is the last char (not sure what substr does if start index > string len)

    It must be Monday...

    While they surely serve to increase the ENTROPY of any given application, Mondays aren't really an excuse for being a terrible architect. Also, EVERYTHING.INC probably wasn't built in a day.
  • Eric L (unregistered) in reply to Juifeng

    Thats the reason that real languages like .Net include globalization :)

  • (cs) in reply to Walleye
    Walleye:
    EatenByAGrue:
    The signal that this was a WTF is a file named "everything.inc", because any code named "everything" is: 1. Misnamed. 2. Full of foolishly reimplemented library calls like this one. 3. Not at all modular.

    I wish I had an "everything.inc". I'd never have to write new code again!

    You joke, but I've seen it over and over, and not just in php...I've seen this crap in java.

    There is a certain type of programmer that goes through life with one big honking file in which he includes every method he has ever written, and he imports that massive chunk of crap code into nearly every program he writes.

    The worst one I've ever seen was in VB and it was (not joking) 1.5megs of crappy functions dealing with everything from data abstraction, to layout (hardcoded html included), to character manipulations, and to add insult to injury, it was compiled into a DLL, and worse, he had multiple versions of it that all did different things.

    I dealt with webapps this joker wrote that were about 50k of app, and about 3 megs of library.

  • chw (unregistered)

    just use str_replace('$', '', $input) -- no need for an arry. WTF!

  • bramster (unregistered)

    OK.

    So does str_replace take care of

    $50 $50,000 $50.5 $50.50 40.15 50.00$

    I've had to deal with this kind of thing, in the same data file.

    Perhaps Brian wrote "everything" when php was brand new, and all the fancy functions were not in the library.

  • Ryan (unregistered)

    Pop quiz, what does this return? fixString("ABBBA", array("B");

    1. AA
    2. ABA
    3. ABBA

    The answer indicates just how broken this function is.

  • (cs)

    At least outputting it in the correct internationalized format is easy enough. Here's Italian, to two decimal places:

    setlocale(LC_MONETARY, 'it_IT');
    echo money_format('%.2n', $number);
    
  • Michael (unregistered) in reply to Satanicpuppy
    Satanicpuppy:
    Matt:
    cod3_complete:
    I've seen this kind of WTF coding far too much in my time and it just has to stop. Reimplementing an existing API is one of the worst damn things anyone can do. Unfortunately, the PHP api is inconsistent in both naming conventions and use of underscores so it can be easy to get lost when the language looks like spaghetti and is poorly designed.
    ++

    PHP sucks because:

    1. No types and therefore silent conversions where you don't want them ( === should NOT be nessisary)
    2. No exceptions (in PHP4 which everyone still uses)
    3. No naming conventions for functions
    4. No namespaces

    No naming conventions? Thats a snobby nit to pick.

    I agree, PHP has plenty of naming conventions.

    Oh wait....

  • Mike G. (unregistered)

    ltrim($price,'$');

  • John Hardin (unregistered)

    TRWTF is: an order form that lets the user enter the price themselves?

  • (cs)

    Jared, you're doing it wrong.

    People reading through the codebase should only have one library routine that does each thing.

    Maybe fixString() was redundant, but now the company's codebase has 2 redundancies.

    Remember, code is written once (sorta) and read many times. Two years from now, when someone reads through the code, and they see some people using fixString(), and others using str_replace(), are they going to know why? They probably will not imagine the petty office politics that people are passive-aggressively fighting through the source repository.

  • Mike G. (unregistered) in reply to Matt
    Matt:
    PHP sucks because:
    1. No types and therefore silent conversions where you don't want them ( === should NOT be nessisary)
    2. No exceptions (in PHP4 which everyone still uses)
    3. No naming conventions for functions
    4. No namespaces
    1. That's a nice time-saving feature as far as I'm concerned. Different strokes for different folks..
    2. PHP4 may suck, but it's no longer supported. I use PHP5 exclusively.
    3. Meh, yeah this is an issue, but hardly enough to get my blood boiling...
    4. PHP5.3 has namespaces
  • AP (unregistered) in reply to SlyEcho
    What happens when I write "$1,000.00"?

    Behold! This is the glory of fixString()!! You can pass it an array with "$" AND "."

  • jbrecken (unregistered) in reply to Ryan
    Ryan:
    Pop quiz, what does this return? fixString("ABBBA", array("B");

    An unmatched parentheses syntax error.

  • mbs (unregistered) in reply to Zap Brannigan

    ah, much better.

  • (cs) in reply to Ryan

    A fatal error, specifically E_PARSE.

  • dave (unregistered) in reply to abx
    abx:
    Juifeng:
    In some parts of the world, $1,000 means what you'd type as "$1.000". So there is no way for PHP to really understand commas and dots that easily.
    In some programming languages of the world, cultural differences like these are anticipated and taken care of. Of course, casting a string to an int should never be allowed, but if it was, the culture of the computer it runs off could be assumed (as long as there are ways to do it which lets you specify otherwise)
    This is php, which is usually run on a different computer than that of the user. If the user is from some inferior location in space/time and does not use 1,234·56 (which the server expects), their request would be erroneously processed.

    You could of course look through the request header for a nationality code and then hope that the user has configured his browser AND knows how to write numbers. It is a bit of a burden to lay on your users, though.

  • (cs) in reply to Ryan
    Ryan:
    Pop quiz, what does this return? fixString("ABBBA", array("B");
    1. AA
    2. ABA
    3. ABBA

    The answer indicates just how broken this function is.

    I get "AA" (after fixing the function call). Which is what I would expect from stripping all the "B"s out of "ABBBA". What's the problem with that answer?

  • Matt (unregistered) in reply to Satanicpuppy
    Satanicpuppy:
    No naming conventions? Thats a snobby nit to pick.
    I don't care that they don't enforce naming conventions on you, the programmer, but when the in-built libraries use_different NamingConventions 4evry function_different it means you can't guess the name of the function you want, and since there's no types, OO (in php4) or namespaces, you can't rely on intellisense helping you out.
    Satanicpuppy:
    The typing issue is pretty vague too; php does suck for the whole weak/dynamic typing thing, but languages like Python also have dynamic typing (though not weak typing), and it adds a lot to usability over pissy static/strongly typed languages like java.
    Just because java sucks, doesn't make PHP good. In C# you can define implicit overloads to objects that you want to silently type themselves (and you can even create your own PHPVariable class that does all of the silent evilness that PHP does for typing if you hate yourself).

    Weak typing is great for tiny scripts - you can write them in 20 seconds, hit F5 and get an answer. If you're dealing with programs more than 1000 lines of code, or where maintenance is required, strong typing saves a whole load of time in reading documents, source-code and WTFs.

    Satanicpuppy:
    Finally, php4 is now officially unsupported, so it's not entirely fair to say that "everyone" is using it. I don't use php all that much, and but I've been using 5 for a good while.
    Thank god for small mercies.
    Satanicpuppy:
    Php is fine for what it does. Sure it can produce crap code, but it's not a requirement. I'll agree with you on the namespace thing though; that's a royal p.i.t.a.

    It doesn't just allow you to make bad code, it encourages it. If a function doesn't specify the types that the arguments take, then you're just asking for trouble.

  • (cs) in reply to Matt
    Matt:
    It doesn't just allow you to make bad code, it encourages it. If a function doesn't specify the types that the arguments take, then you're just asking for trouble.

    But that's just dynamic typing for you. Lots of things use dynamic typing, PHP, Python, Javascript, Ruby, Lua, XML etc. For a lot of things (eg passing the right types of parameters to a function) static typing does have an advantage in that it will find lots of errors at compile-time, but dynamic typing also works well (hence the reason it is used so much).

    So, you can't say 'PHP is crap because it uses dynamic typing'. If that were the case, you've pretty much condemned all languages used for web development...

Leave a comment on “My str_replace() Can Beat Up Your str_replace()”

Log In or post as a guest

Replying to comment #:

« Return to Article