gpt4 book ai didi

PHP preg_split 如果不在大括号内

转载 作者:行者123 更新时间:2023-12-02 01:22:50 25 4
gpt4 key购买 nike

我正在使用 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

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

我必须使用哪个正则表达式来分割它(用空格分割),但前提是不在大括号内。所以我想把上面的代码变成这个数组:

  1. 你好,世界!
  2. 要么
  3. 这个
  4. 颜色
  5. 蓝色
  6. 红色
  7. #00AA00
  8. 要么
  9. 这个
  10. 字体
  11. Arial 黑色
  12. 摩纳哥
  13. 哪里
  14. 两者
  15. 这个
  16. 颜色
  17. 字体
  18. 已下定决心
  19. 随机

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

我该怎么做?

提前致谢。

最佳答案

使用这样的东西怎么样:

$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]);

这会让你:

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)

您只需迭代这些结果即可;以 { 开头并以 } 结尾的单词将是您的“重要”单词,其他单词将是其余单词。


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

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

或者,就像你说的,使用 strpos 和 strlen 也可以工作;-)

关于PHP preg_split 如果不在大括号内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1351980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com