str_replace only after first space and not after 2nd.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aprestong
Forum Newbie
Posts: 5
Joined: Thu Aug 03, 2006 2:47 pm

str_replace only after first space and not after 2nd.

Post 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...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
aprestong
Forum Newbie
Posts: 5
Joined: Thu Aug 03, 2006 2:47 pm

Post 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...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You can explode() more than once. explode() the lines apart, explode() each line apart, etc etc..
Post Reply