• Phil (unregistered) in reply to mabinogi
    mabinogi:
    jonnyq:
    1. Ok, sure, but Ruby and Python are the same way. Beyond that, what are your web development options? JSP and ASP? I personally don't have a problem with ===, but I agree that it's counterintuitive for a newbie.
    No, they are not. They are both strongly typed - there's no type conversion done. Methods allow you to pass any type in, but that's not the same thing at all as being typeless or doing silent conversions. a string is always a string, unless you explicitly call a function to parse it as something else.

    I haven't used PHP, but Ruby also doesn't (by default) use === in the same way PHP seems to (which, from what I gather, involves a type comparison in PHP). === in Ruby has to do with ranges/matches. I believe it's used behind the scenes in case statements, which is what lets you do stuff like use a range as a match condition when switching on a number, or a regex when switching on a string. (1..2) doesn't equal 2 so (1..2) == 2 is false, but 2 is within the range of 1 to 2, inclusive so (1..2) === 2 is true. Same idea with regexs. To compare types of two objects in Ruby you'd do something like 2.class == 2.0.class (which is false).

    It can be overloaded, though, so someone would be free to implement === to do whatever they wanted (please don't!).

  • DrGuz (unregistered) in reply to vt_mruhlin
    vt_mruhlin:
    "Great!" Jared replied, clenching my teeth.

    He was clenching your teeth? That sounds uncomfortable.

    And I thought to yourself, "You expect me to stick your tongue out this way? Don't hold my breath."

  • Tina Woodward (unregistered)

    Hey, a $1,000 is a $1,000 right? Works for me.

    Jiff www.anonymize.us.tc

  • Edward (unregistered) in reply to Ryan

    That code will return "Parse error. Missing parenthesis." - or something of the likes :)

  • Chris (unregistered)

    Fixed.

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

  • Brian (unregistered) in reply to dusoft
    dusoft:
    And no, not everyone uses PHP 4.
    That's right! I for one use PHP 3 if PHP 2 is not available.
  • Mr.' (unregistered) in reply to Matt
    Matt:
    PHP sucks because: ... 2. No exceptions (in PHP4 which everyone still uses) ...
    PHP 5 has exceptions, but they're almost useless since they're not thrown by any of the core library functions. WTF?
  • rock (unregistered) in reply to Juifeng

    This is what locale functions are for!

  • Tama (unregistered) in reply to Andrew
    Andrew:
    Yeah, but not always. Take Java's StringBuilder and StringBuffer. StringBuffer exists because people kept "Reimplementing an existing API" making the original StringBuilder run faster.

    Huh? StringBuffer has been there for essentially forever (since 1.0) while StringBuilder has only been added in Java 5 because in most cases, people were using StringBuffer in a single thread and were paying the cost of synchronization for nothing...

  • Jason (unregistered) in reply to Walleye
    Walleye:
    I wish I had an "everything.inc". I'd never have to write new code again!

    Perhaps we can write a program to randomly generate every possible PHP function, save its output, and include it in every program. Then you just find the function you want and call it. We could call it "the library of Babel". :)

  • DLLs are OK (unregistered) in reply to Satanicpuppy

    Oh get off your high horse already; 3MB is a small price to pay for a stable, reusable library that probably cuts development time in half.

  • iNFiNiTyLoOp (unregistered)

    This find-first-occurance-starting-at-index and string-concatenation approach will be faster than a dozon str_replace() calls any day, but speed alone doesn't matter to some here.

    Once I made a multiple replace function. It could be used for general string swapping without a reserved intermediate string replacement. I made it to do replacement of batchfile-type variable names with constants before evaluating it. (Yes I had properly escaped the constants first.) Multiple calls to replace can't accomplish this without reserved strings and risking undesired nested expansion that's dependent on the order of the calls.

  • Opacity 50% (unregistered) in reply to lostdreamer
    lostdreamer:
    trwtf is that the array function is not necessary in his 'better way' :P

    TRWTF in your comment is that array() is not a function, but rather a language construct. ;P

  • blink (unregistered) in reply to Satanicpuppy

    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.

    I'm old enough that my "big honking file" has routines that predate the VB functions they are 're-writing'. For example, Replace().

    Even recently I wrote routines to strip off the time or date from a DateTime, only to find that there are built in .TimeOfDay and .Date functions as part of the Date type. Dunno when they got added. Maybe they were there all along.

    When I started programming, there wasn't any such thing as a date variable :-O I had my own routine to parse a date string into an integer (which represented the number of days since a certain magic date).

    (Actually I remove functions from my big honking file as they become redundant, but it's funnier to claim they are still there)

  • more randomer than you (unregistered) in reply to abx
    abx:
    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.

    Seven days if I remember correctly.

  • (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'd just have to call the existing functions in your new code, which you wouldn't have to write, because it'd already be in everything.inc, so you'd just have to call it from your new code, which stack overflow

  • anonymous (unregistered) in reply to planck

    Captcha facilisis thinks that given solution is TRWTF. What will be if user enters $1000.25? 100025? OOPS. Someone really screwed up.

  • anonymous (unregistered) in reply to anonymous
    anonymous:
    Captcha facilisis thinks that given solution is TRWTF. What will be if user enters $1000.25? 100025? OOPS. Someone really screwed up.

    it was an answer to

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

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

  • Barf4Eva (unregistered) in reply to Technical Thug
    Technical Thug:
    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.

    Ouch, there is truth to this... SO, the solution is to get rid of all fixString() calls and replace them with str_replace() everywhere they reside, while carefully considering differences in behavior. :)

    What a utopia, right? What's the ROI from the fast-paced business's business peoples' perspectives?

    Although it is really worth it in the long run. It benefits both employees, the companies, and overall morale. Working on plugging holes in sinking ships is not conducive to employees, the companies, and overall morale.

    I advocate battling past office politics.

  • equex (unregistered) in reply to Matt

    [quote user="Matt"][quote user="cod3_complete"] 2. No exceptions (in PHP4 which everyone still uses) [/quote]

    For certain values of everyone maybe...for the rest of us, we are reading up on PHP 6 after several years on PHP5.

  • bucket (unregistered) in reply to AP

    That would make it, "1,00000"... yay for accidentally multiplying it by 100.

  • bucket (unregistered) in reply to bucket

    That was in reponse to this, naturally:

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

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

  • Morten (unregistered) in reply to bucket

    As Matt points out a real job is one where you are allowed to exceed a whole THOUSAND LINES of code!!!!! or writing maintaiable code.

    No you don't need to wonder anymore

  • (cs) in reply to abx
    abx:
    snoofle:
    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.

    Indeed, it was built in 6 days, and the 7th was a day of rest.

  • Tomas (unregistered)

    You are going to write separate str_replace() for each input field? What about if they want to filter eg thousand separator? Another str_replace() for each field? It is not brilliant (and not secure) but this is why they have some lib for 'everything' :))

  • AdT (unregistered) in reply to d00d
    d00d:
    and what would be an example for that worst-case complexity? at first glance I would say the inner loop is executed at most n times IN TOTAL since the length decreases every time. Yields an O(n²) if all characters get removed, plus the obvious O(nm) from strpos executed for every character to be removed.

    Good point. On second thought, the worst case complexity seems to be "only" O(n² + nm). Of course, strictly speaking this doesn't contradict my previous notion. ;-)

  • AC (unregistered) in reply to abx

    [quote user="abx"][quote user="Juifeng"]the culture of the computer it runs off could be assumed[/quote]

    Great. We'll use IP geolocation for that!

  • (cs) in reply to Morten
    Morten:
    As Matt points out a real job is one where you are allowed to exceed a whole THOUSAND LINES of code!!!!! or writing maintaiable code.

    No you don't need to wonder anymore

    Clueless.

  • Rhialto (unregistered) in reply to Steve
    Steve:
    It seems to me that you should only strip leading dollar signs. If the user types
    1$00
    when they meant to type
    1400
    then arguably that's an error which should be trapped.
    Or they could have meant 1 Escudo, if they mean the Portuguese currency before the Euro. Yes, they did use a $-sign as a decimal separator.
  • Cpt (unregistered)

    And now the company goes international and deals with real currencies like Yen, Euro, Pounds and what not. And there goes the site, down again because Jared did not want to listen to the more experienced teamlead who did in fact envision other characters to be excluded as well. Perhaps not as efficient as possible, but it would work... but noooo.... not Jared... eh, Jared?

  • anon (unregistered) in reply to Tama

    Agreed, but have you ever heard of lock elision ... ?

  • Rob Baillie (unregistered)

    "Jared shook his head and sighed. Instead of including the entire, 800-line everything.inc file in his page, he opted for the built-in replace():"

    Go forbid that he would consider simplifying "fixString" at the same time. Or stripping its usage out of the existing system.

    Why is it that so many WTFs end with papering over the cracks and moving on?

  • (cs) in reply to Evo
    Evo:
    There are even functions in there of which the number of arguments is incorrect in the documentation. Go figure.

    I do work most every day in php, among other languages, and tbh i have never encountered documentation on a function with incorrect number of arguments. I'm not saying your claim is or is not true, but only that I've never encountered it, and this is not due to that I have no need to use a generous range of the available functionality of the language.

    If you find such a thing, make yourself useful and submit a bug report to the documentation team that works as volunteers and someone will check it out and make the changes in cvs. If ever in doubt, one can always look at the source to see the internals, but like I mentioned, I've never encountered this and tbh I feel you are exaggerating for dramatic impact the frequency of something like this happening.

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

    What happens when you write "£1,000.00" .....

  • foo (unregistered) 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
    Strict typing is weak. Period. Why do you think strict typing languages are implementing dynamic typing? To be more dynamic.. you utter tool.
  • Jay (unregistered) in reply to Gary Skinner
    Gary Skinner:
    Matt:
    I have no problem in condemning all of the languages used for web-development, particularly given the average level of competence from web-developers is roughly zero. That's why they don't have real jobs.

    Please Matt, inform us as to what a 'real' job is. I am curious.

    Community organizer.

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

    We ignore the punctuation, interpret what's left as an integer, and bill the customer's credit card for one hundred thousand dollars. So what's the problem?

  • Jay (unregistered) in reply to vt_mruhlin
    vt_mruhlin:
    "Great!" Jared replied, clenching my teeth.

    He was clenching your teeth?

    Anyone in the audience with the power of telekinesis, please raise my hand.

  • Jay (unregistered) in reply to operagost
    operagost:
    notromda:
    include "cluestick.inc"

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

    You should have struck the ground five or six times; then you would have defeated Brian and completely destroyed him. But now you will defeat him only three times.

    Wow, talk about an inside joke. I feel a certain irrational smugness for catching the allusion, like, "Ooh, I wonder how many readers here even know who Elisha was." Why is understanding an inside joke emotionally gratifying? An amusing psychological study. Perhaps I can get a government grant to research it.

  • DavidTC (unregistered)

    TRWTF is using array('$') instead of '$'.

    Just because str_replace() can take an array instead of a string doesn't mean you should randomly build a single-element one and pass that in.

    Also ltrim() might have been a better solution. OTOH, it wouldn't handle -$20, so maybe not.

    Also, I at least consider it best practices to use single quotes instead of double quotes for stuff that isn't supposed to have variables evaluated in it, although that's not that important.

  • mattw (unregistered) in reply to Matt
    1. Dynamic>Strong. Pfft. If you used something like ObjC you'd probably have an aneurysm.
    2. "Everyone" does not use php4. php4 has been EOL'd.
    3. There is a naming convention for functions. Lowercase, underscored, like all php API functions. You can break it if you want to, say, if you're a camelCase whore.
    4. http://us2.php.net/manual/en/language.namespaces.php - noob.
  • Jiffy Whipper (unregistered)

    Fight, Fight Fight Fight! LOL Fight!!!!!

    Jiffers www.anonymize.us.tc

  • Mr.'; Drop Database -- (unregistered) in reply to mattw
    mattw:
    1. Dynamic>Strong. Pfft. If you used something like ObjC you'd probably have an aneurysm. 2. "Everyone" does not use php4. php4 has been EOL'd. 3. There is a naming convention for functions. Lowercase, underscored, like all php API functions. You can break it if you want to, say, if you're a camelCase whore. 4. http://us2.php.net/manual/en/language.namespaces.php - noob.
    1. Dynamic typing and strong typing are orthogonal. Most dynamically typed languages are strong. If you use PHP for any reasonable length of time, you'll find its dynamic, weak type system to be a burden. 2. If you use PHP 5, you'll find that it doesn't throw exceptions from the standard library, making them useless for any of the purposes that programmers would want exceptions for. 3. If you use PHP, you'll find that lots of core functions are multiple words without underscores separating them. You don't use PHP, do you? 4. Agreed.
  • Dave Edelhart (unregistered)

    And even that is verbose:

    $str = ltrim($str, '$');

  • (cs) in reply to Jay
    Jay:
    Wow, talk about an inside joke. I feel a certain irrational smugness for catching the allusion, like, "Ooh, I wonder how many readers here even know who Elisha was." Why is understanding an inside joke emotionally gratifying? An amusing psychological study. Perhaps I can get a government grant to research it.
    I didn't feel any smugness about it; just heaved a sigh at all the wasted years.
  • IByte (unregistered) in reply to \
    \:
    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.

    Well, I get paid for a fixed number of hours. He spent 10 minutes coding. I spend 1 minute coding and 9 minutes reading TheDailyWTF.com ;)

  • (cs) in reply to operagost
    operagost:
    notromda:
    include "cluestick.inc"

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

    You should have struck the ground five or six times; then you would have defeated Brian and completely destroyed him. But now you will defeat him only three times.
    I think you're using the wrong Pokemon, there...

  • Anonymous Sniveling Coward (unregistered)

    This is a classic case of reinventing the wheel when unnecesary (and possibly slow and dangerous).

    The worst such case was code I saw which worked on a PostgreSQL server I was paid to install. All of the code was in stored procedures and all of the stored procedures which inserted new records did something like this to create a new ID number.


    SELECT INTO newid MAX(id) FROM table; SELECT INTO newid newid + 1;

    It might have been creative, but it was slow and buggy, causing lots of duplicate errors and really straining the database (since MAX is slow due to postgres' form of concurrency).

  • thinice (unregistered)

    floatval();

  • wholenike (unregistered)

    This is Hamlet Shoes Trading Co. LTD., which is united by lots of footwears manufacturers in Fujian of China. We deal with brand shoes like Nikes, Adidas, Puma, Timberland boots, etc. We have especially Nikes like Air Jordan retro,nike shox (Nz Oz R3 R4 R5 Turbo), Air Max (LTD TN 90 95 97 2003 2004 2005 180 360), Air force one,James, Dunks,and other products: bape, prada,Gucci shoes, jeans,handbags, lacoste,polo,bape jacket and so on. We can supply mixed colours and sizes as you like. Drop shipping can be done also. Normally we need 24 working hours to process your order after receipt of payment. You can expect to receive the shoes in around 5-7days. Buyers please feel free to contact us: E-mail & MSN: [email protected] Browse our website:http://www.wholenike.com. We are waiting for you. Best regards!

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