pro_php thread: Help with preg_split please.
Hmm.... your pattern looks incorrect, since you're really only matching the
string "{}". What you're saying is "Split all the segments of the subject
string that are separated by '{}'".
Also, preg_split returns an array, so you can't expect echo() to output it
correctly. Use print_r for outputting the contents of arrays (or any variable,
for that matter.)
I've posted this function a thousand times, because I use it for EVERY script I
write, even the toy scripts I write to answer questions in this forum.
function printr($var, $desc = '')
{
echo "<PRE>";
if($desc != '')
{
echo "$desc:\n";
}
print_r($var);
echo "</PRE>\n";
}
Back to your script. I think you'd be better off with preg_match or
preg_match_all, since you seem to want items that are contained within a
pattern, not separated by one.
$pattern = "/{([^}]+)}+/";
This pattern searches for one or more instances of {...} in a string. Breaking
down the pattern, you see that I look for an open curly brace, then one or more
characters that are _not_ the closing curly brace, then the closing curly
brace. I parenthesize the text found within the curly brace.
Here's a short test script and it's output:
---------------------------------------------
<?php
function printr($var, $desc = '')
{
echo "<PRE>";
if($desc != '')
{
echo "$desc:\n";
}
print_r($var);
echo "</PRE>\n";
}
$pattern = "/{([^}]+)}/";
$games = '{gta3}{madden 2003}{vice city}';
if(preg_match_all($pattern, $games, $fgames))
{
printr($pattern, '$pattern is');
printr($fgames, '$fgames is');
}
?>
---------------------------------------------
Output:
---------------------------------------------
$pattern is:
/{([^}]+)}/
$fgames is:
Array
(
[0] => Array
(
[0] => {gta3}
[1] => {madden 2003}
[2] => {vice city}
)
[1] => Array
(
[0] => gta3
[1] => madden 2003
[2] => vice city
)
)
---------------------------------------------
Take care,
Nik