gpt4 book ai didi

php - 将字符串拆分为二元语法,忽略某些标签

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:42:20 24 4
gpt4 key购买 nike

考虑以下字符串:

I have had the greatest {A} {B} day yesterday {C}

我想用二元语法创建一个数组,忽略所有标签(标签在{括号}之间)

[0] => I-have
[1] => have-had
[2] => had-the
[3] => the-greatest
[4] => greatest-day
[5] => day-yesterday

在 PHP 中,执行此操作的最佳方法是什么?使用正则表达式或对“”展开,然后遍历所有单词?我在这里开始时遇到问题,所以任何帮助将不胜感激:)

最佳答案

使用 explode 使它变得足够简单:

$string="I have had the greatest {A} {B} day yesterday {C}";

$words=explode(" ",$string);

$filtered_words=array();

foreach($words as $w)
{
if(!preg_match("/{.*}/",$w))
{
array_push($filtered_words,$w);
}
}


$output=array();

foreach(range(0,count($filtered_words)-2) as $i)
{
array_push($output,$filtered_words[$i] . "-" . $filtered_words[$i+1]);
}

var_dump($output);

输出是:

array(6) {
[0]=>
string(6) "I-have"
[1]=>
string(8) "have-had"
[2]=>
string(7) "had-the"
[3]=>
string(12) "the-greatest"
[4]=>
string(12) "greatest-day"
[5]=>
string(13) "day-yesterday"
}

关于php - 将字符串拆分为二元语法,忽略某些标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221092/

24 4 0