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


$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.";

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

所以提取的文本将是

$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 ";

注意,单词计数在我的中不起作用

假定为"排版行业"one_answers"20世纪60年代"是独一无二的,必须在我的绳子上。

如何查找和提取这样的内容?

您应该使用一个简单的(.*)(捕获所有内容(正则表达式,该正则表达式由搜索字符串/$start(.*)$end/包围。由于搜索字符串可能包含regex特殊字符,您还应该使用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];

或者,您也可以使用关键字拆分字符串

$start = "typesetting industry.";
$end = "1960s";
$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.";
$exploded = explode($end, explode($start, $string)[1]);
echo $exploded[0];

最新更新