php重叠正则表达式
我正在尝试查找Regex语句的所有结果,该语句用于查找要搜索的单词以及前后的十个单词 我的问题不是Regex语句,而是语句中的重叠 我找了很多,但找不到解决方案,请帮助我php重叠正则表达式,php,regex,preg-match,Php,Regex,Preg Match,我正在尝试查找Regex语句的所有结果,该语句用于查找要搜索的单词以及前后的十个单词 我的问题不是Regex语句,而是语句中的重叠 我找了很多,但找不到解决方案,请帮助我 输入: 维基百科是一本免费的在线百科全书,由世界各地的志愿者创建和编辑,由维基媒体基金会主办 搜索词:和 我想要的输出: 维基百科是一个免费的在线百科全书,由世界各地的志愿者创建和编辑,并由 o 在线百科全书,由世界各地的志愿者创建和编辑,由维基媒体基金会主办 更新 因为需求不够明确,我不得不改变整个解决方案 PHP代码:
输入: 维基百科是一本免费的在线百科全书,由世界各地的志愿者创建和编辑,由维基媒体基金会主办 搜索词:和 我想要的输出:
更新 因为需求不够明确,我不得不改变整个解决方案 PHP代码:
$str = 'Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation';
// Split into words
$words = preg_split('~ +~', $str);
// Find all indexes of our keyword `and`
$indexes = array_keys($words, 'and');
// Number of preceding or following words
$numberOfWords = 10;
// Iterate over them
foreach ($indexes as $i) {
// Use `array_slice()` to extract words before and after our keyword and join them together using `implode()`
$sentences[] = implode(' ', array_slice($words, ($i - $numberOfWords > 0) ? $i - 10 : 0, $i + $numberOfWords));
}
print_r($sentences);
输出:
Array
(
[0] => Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by
[1] => online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation
)
更新
因为需求不够明确,我不得不改变整个解决方案
PHP代码:
$str = 'Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation';
// Split into words
$words = preg_split('~ +~', $str);
// Find all indexes of our keyword `and`
$indexes = array_keys($words, 'and');
// Number of preceding or following words
$numberOfWords = 10;
// Iterate over them
foreach ($indexes as $i) {
// Use `array_slice()` to extract words before and after our keyword and join them together using `implode()`
$sentences[] = implode(' ', array_slice($words, ($i - $numberOfWords > 0) ? $i - 10 : 0, $i + $numberOfWords));
}
print_r($sentences);
输出:
Array
(
[0] => Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by
[1] => online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation
)
请将输入字符串添加到您的问题中。以及我们目前的状态下所需的输出。您是否尝试使量词取消冻结?像那样
{0,10}?
或者使用U
标志?是否有人因为preg\U match\U all()
中的$data[]
起作用而陷入大脑停滞?但是,如果你做你自己的功能,你不能做这样的事情<代码>函数foo(&$r){var_dump($r);}$data=array();foo($data[]);打印(数据)代码>您需要两个输出吗?!请将输入字符串添加到您的问题中。以及我们目前的状态下所需的输出。您是否尝试使量词取消冻结?像那样{0,10}?
或者使用U
标志?是否有人因为preg\U match\U all()
中的$data[]
起作用而陷入大脑停滞?但是,如果你做你自己的功能,你不能做这样的事情<代码>函数foo(&$r){var_dump($r);}$data=array();foo($data[]);打印(数据)代码>您需要两个输出吗?!非常感谢,我可以为每个单词匹配最长的句子吗?我不想要每个结果?最长的意思是只有一句话。你只需要最长的一句话吗?不,我希望搜索的每个单词都是最长的,在你的搜索结果中,我希望0和4是这个单词的最佳匹配,在这之前和之后的10个0和4是第一个和而不是第二个的两个匹配。非常感谢,我可以为每个单词匹配最长的句子吗,我不想要每个结果?最长的意思是只有一句话。你只需要最长的一句话吗?不,我希望搜索的每个单词都是最长的,在你的搜索结果中,我希望0和4是单词的最佳匹配,10是前后的0和4是第一个和第二个的两个匹配。