PHP preg_split如果不在花括号内

2 php regex programming-languages preg-split

我是一个使用PHP的脚本语言解释器.我用这种脚本语言编写了这段代码:

write {Hello, World!} in either the color {blue} or {red} or {#00AA00} and in either the font {Arial Black} or {Monaco} where both the color and the font are determined randomly
Run Code Online (Sandbox Code Playgroud)

(是的,很难相信,但那是语法)

我必须使用哪个正则表达式来拆分它(用空格分割),但仅限于不在大括号内.所以我想把上面的代码转换成这个数组:

  1. 你好,世界!
  2. 颜色
  3. 蓝色
  4. 要么
  5. 红色
  6. 要么
  7. #00AA00
  8. 字形
  9. Arial Black
  10. 要么
  11. 摩纳哥
  12. 哪里
  13. 颜色
  14. 字形
  15. 决心
  16. 随机

(大括号内的字符串以粗体显示在上面)大括号内的字符串必须是每个元素.所以{Hello,World!}不能:1.你好,2.世界!

我怎样才能做到这一点?

提前致谢.

Pas*_*TIN 5

怎么样使用这样的东西:

$str = 'write {Hello, World!} in either the color {blue} or {red} or {#00AA00} and in either the font {Arial Black} or {Monaco} where both the color and the font are determined randomly';

$matches = array();
preg_match_all('#\{.*?\}|[^ ]+#', $str, $matches);

var_dump($matches[0]);
Run Code Online (Sandbox Code Playgroud)

哪个会给你:

array
  0 => string 'write' (length=5)
  1 => string '{Hello, World!}' (length=15)
  2 => string 'in' (length=2)
  3 => string 'either' (length=6)
  4 => string 'the' (length=3)
  5 => string 'color' (length=5)
  6 => string '{blue}' (length=6)
  7 => string 'or' (length=2)
  8 => string '{red}' (length=5)
  9 => string 'or' (length=2)
  10 => string '{#00AA00}' (length=9)
  11 => string 'and' (length=3)
  12 => string 'in' (length=2)
  13 => string 'either' (length=6)
  14 => string 'the' (length=3)
  15 => string 'font' (length=4)
  16 => string '{Arial Black}' (length=13)
  17 => string 'or' (length=2)
  18 => string '{Monaco}' (length=8)
  19 => string 'where' (length=5)
  20 => string 'both' (length=4)
  21 => string 'the' (length=3)
  22 => string 'color' (length=5)
  23 => string 'and' (length=3)
  24 => string 'the' (length=3)
  25 => string 'font' (length=4)
  26 => string 'are' (length=3)
  27 => string 'determined' (length=10)
  28 => string 'randomly' (length=8)
Run Code Online (Sandbox Code Playgroud)

你必须迭代这些结果; 以{开头}开头的那些将是你的"重要"词汇,其他人将是其余的.


评论后编辑:识别重要单词的一种方法是这样的:

foreach ($matches[0] as $word) {
    $m = array();
    if (preg_match('#^\{(.*)\}$#', $word, $m)) {
        echo '<strong>' . htmlspecialchars($m[1]) . '</strong>';
    } else {
        echo htmlspecialchars($word);
    }
    echo '<br />';
}
Run Code Online (Sandbox Code Playgroud)

或者,就像你说的那样,使用strpos和strlen也会起作用;-)