/    Sign up×
Community /Pin to ProfileBookmark

regular expression question

Hi,

Suppose I have the variable below.

$description = “{This|That|There} blah blah {Him|Her|It}”;

How could I use regular expression to use only 1 of the words within each bracket.

Thanks

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogApr 23.2009 — Are you saying you just want to randomly choose one of the words in each bracketed expression, or something else?
Copy linkTweet thisAlerts:
@Blizzard84authorApr 23.2009 — Hi NogDog,

Thanks for the quick reply.

Yes, I want only one of the words randomly or not.

Thanks
Copy linkTweet thisAlerts:
@NogDogApr 23.2009 — I suppose you could do something with preg_replace_callback(), though the specifics would depend on how you want to actually choose which word.
[code=php]
<?php
$description = "{This|That|There} blah blah {Him|Her|It}";
function chooseWord($matches)
{
$words = explode('|', trim($matches[0], '{}'));
return $words[array_rand($words)];
}
$new = preg_replace_callback('/{[^}]+}/', 'chooseWord', $description);
echo $new;
[/code]
Copy linkTweet thisAlerts:
@Blizzard84authorApr 24.2009 — Hi NogDog,

This was exactly what I was looking for.

Is there a way to grab combinations of words using this way based on a user_id? Not really liking the randomization

So i need

1, 1

1, 2

1, 3

2, 1

2, 2

2, 3

Thanks for all your help!!
×

Success!

Help @Blizzard84 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...