我正在寻找做到这一点的最好方法......是否存在一些方便的正则表达式?或者我应该以某种方式逐段播放它?
好的,我有这样一句话:
"The rooms rooms and rooms again were great, the food was not but the beds were extremely comfortable."
我有一系列项目(分界符):
array('food','room','bed');
我想以某种方式神奇地获取这些单词之间的句子部分...就像将它分开(从一个分隔符到另一个分隔符),如果它是可以理解的......
第一部分:
"The"
第二部分(直到距离数组最近的项目(分隔符):
"rooms "
第三部分:
"rooms and "
第四部分:
"rooms again were great, the"
第五部分:
"food was not but the ".
第四部分:
"beds were extremely comfortable."
基本上将句子从一个关键词重复分配到另一个关键词。
分界点的意思是将句子分开......所以只需匹配它......如果在句子中有一个单词“rooms”,它就会与分隔符“room”相匹配。复数并不重要,重点是根据分界符(数组中的项目)将句子拆分为多个部分。
请问好吗?
答案 0 :(得分:4)
可以使用lookahead分割:
$pattern = '/(?=room|food|bed)/i';
$str = "The rooms rooms and rooms again were great, the food was not but the beds were extremely comfortable.";
print_r(preg_split($pattern, $str));
输出(test @ eval.in)
Array
(
[0] => The
[1] => rooms
[2] => rooms and
[3] => rooms again were great, the
[4] => food was not but the
[5] => beds were extremely comfortable.
)
已使用i (PCRE_CASELESS)
modifier。可能希望将\b
word-boundaries添加到某些字词中。