Reputation: 5413
I presume this is a weird sort of thing that I'm looking for.
I have the following text string:
$string = "The compass is pointing <north|south|east|west> towards <London|Paris|Rome>";
Somehow I want to parse this to obtain any of the following outputs:
For each set of < > in the text string I need to convert the contents into an array (using explode("|",$string)
?), then run array_rand
on that array to get the key for the option we will display, then just read the array and return that value.
The problem is, I have very next to no experience with text parsing, but I'd guess you'd use preg_replace
in this type of problem.
I'd appreciate if anyone could help me get started.
Upvotes: 1
Views: 61
Reputation: 20873
You could use preg_replace_callback()
to execute a function that chooses a random replacement.
$string = "The compass is pointing <north|south|east|west> towards <London|Paris|Rome>";
$callback = function ($match) {
$opts = explode('|', $match[1]);
return $opts[array_rand($opts)];
};
echo preg_replace_callback('/<(.+?)>/', $callback, $string);
The pattern matches <
, any stuff (.+
), and >
. The "lazy" quantifier ?
makes the +
stop when it finds the shortest match, rather than being "greedy" and looking for the longest possible match (which is default behavior). Without it, it would match all the way to the last >
, which is too far.
The ( )
creates a subpattern, so while $match[0]
would be what's matched by the entire pattern (including < >
), $match[1]
will only contain the subpattern (without < >
).
The callback function is called each time a match is found, and it does exactly what you described -- explode()
the list of options and return a random one. The return value then replaces the original match.
Upvotes: 1