正则表达式在句子中获取文本

时间:2017-12-28 15:46:44

标签: php regex

以下是我在语言配置中的一条消息。我想检测随机选择显示给用户的可能单词。

什么是正则表达式,用于检测随机单词的可能性,如粗体

  

[Bravo |很棒|祝贺|做得好| Hoorey | Yeehaa |哇] !你现在要成为赢家。继续!

Php的发展

2 个答案:

答案 0 :(得分:1)

代码

See regex in use here

^[^!]+(?=!)

结果

输入

Bravo! You are now to top to be a winner. Keep going!
Great! You are now to top to be a winner. Keep going!
Congratulations! You are now to top to be a winner. Keep going!
Well done! You are now to top to be a winner. Keep going!
Hooray! You are now to top to be a winner. Keep going!
Yeehaa! You are now to top to be a winner. Keep going!
Wow! You are now to top to be a winner. Keep going!

输出

Bravo
Great
Congratulations
Well done
Hoorey
Yeehaa
Wow

说明

  • ^在行首处断言位置
  • [^!]+匹配!除{/ 1}}之外的任何字符
  • (?=!)肯定前瞻,确保匹配!字面上

答案 1 :(得分:0)

选择要显示的字词,我不确定您是否需要正则表达式。我会做这样的事情:

function getMessage () {
    $words = ["Bravo","Great","Congratulations","Well done","Hoorey","Yeehaa","Wow"];
    return $words [rand (0, count ($words) - 1] . "! You are now to top to be a winner. Keep going!";
}