通过使用2个关键字搜索从字符串中提取一部分

问题描述 投票:0回答:1
$string="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

假设我想从'typesetting industry.'中找到'1960s'$string,并且如果有这些单词/句子,请提取这些单词之间的其余文本并保存到变量中。

因此提取的文本将是>

$extracted_text="Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the ";

请注意,字数统计不适用于我的情况

假定为“排版行业。”和“ 1960年代”是独一无二的,并且必须具备在我的字符串中。

我该如何查找和提取?

$ string =“ Lorem Ipsum只是印刷和排版行业的伪文本。LoremIpsum自1500年代以来就一直是该行业的标准伪文本,当时未知的打印机拿来厨房...

php search extract
1个回答
0
投票
您应该使用一个简单的(.*)(捕获所有内容)正则表达式,并用搜索字符串/$start(.*)$end/括起来。由于搜索字符串可能包含正则表达式特殊字符,因此您也应该使用preg_quote对其进行转义。

$start = preg_quote("typesetting industry."); $end = preg_quote("1960s"); $pattern = "/$start(.*)$end/"; $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; preg_match($pattern, $string, $matches); echo $matches[1];

© www.soinside.com 2019 - 2024. All rights reserved.