Page 1 of 1

str_replace only after first space and not after 2nd.

Posted: Thu Aug 03, 2006 2:53 pm
by aprestong
I'm working on something that is supposed to automatically format recipe abbreviations in a recipe submission database...
I am using str_replace to do this - -
for example

Code: Select all

$recipeingredients = str_replace(" Cups", " C.", $recipeingredients);
$recipeingredients = str_replace(" cups", " C.", $recipeingredients);
$recipeingredients = str_replace(" Cup", " C.", $recipeingredients);
$recipeingredients = str_replace(" cup", " C.", $recipeingredients);
$recipeingredients = str_replace(" c", " C.", $recipeingredients);
$recipeingredients = str_replace(" C", " C.", $recipeingredients);
All is fine and dandy... but I realized while typing

1 C water
will produce
1 C. water

typing

1 C. Carrots
will produce
1 C. C.arrots


Is there a way in PHP where I can essentially say "look after the 1st blank space and not after the 2nd" ??


I'm a newb... sorry if this is a ridiculous question.... I'd like to have only one text area for the entire recipe...

Posted: Thu Aug 03, 2006 2:58 pm
by feyd
unless you wish to use regular expressions, I'd probably use explode() to break the string apart, array_filter() to remove any empty elements and then str_replace() on the second element.

Posted: Thu Aug 03, 2006 3:21 pm
by aprestong
Thanks for your response, feyd-

I have to spend some time reading up on those functions... but I'm not exactly sure it will work for me..
I'm doing these tests on the "ingredients" text area...
I'm sure I am creating mor problems than necessary by wanting to do this all in the same textbox...

for example, the ingredients for a recipe could be

1 cup water
2 tablespoons sugar
2 cups mashed potatoes
4 pints beer

so if I can use str_replace on the 2nd element... but it would be impossible determine what to do on the other lines.

I suppose I wasn't clear enough in my first post... I didnt realize I'm working across multiple lines here...
can I say this:

"check the characters between the first space and second space on the first line and again between the first space and second space on each additional line"
??

i'm probably making this more complicated than it is necessary...

Posted: Thu Aug 03, 2006 3:28 pm
by feyd
You can explode() more than once. explode() the lines apart, explode() each line apart, etc etc..