我需要在一个文本块中定位2个标签,并保持它们之间的任何文本。
例如,如果"Begin“标记是-----start-----,而"End”标记是-----end-----
给定此文本:
rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
-----end-----gcgkhjkn我只需要将文本放在两个标记之间:isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
有什么想法吗?谢谢。
发布于 2012-07-01 05:02:40
以下是几种方法:
$lump = 'rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r-----end-----gcgkhjkn';
$start_tag = '-----start-----';
$end_tag = '-----end-----';
// method 1
if (preg_match('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
echo $matches[1];
}
// method 2 (faster)
$startpos = strpos($lump, $start_tag) + strlen($start_tag);
if ($startpos !== false) {
$endpos = strpos($lump, $end_tag, $startpos);
if ($endpos !== false) {
echo substr($lump, $startpos, $endpos - $startpos);
}
}
// method 3 (if you need to find multiple occurrences)
if (preg_match_all('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
print_r($matches[1]);
}发布于 2012-07-01 05:01:36
试试这个:
$start = '-----start-----';
$end = '-----end-----';
$string = 'rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r-----end-----gcgkhjkn';
$output = strstr( substr( $string, strpos( $string, $start) + strlen( $start)), $end, true);
echo $output;此will print
isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r发布于 2017-05-19 02:59:40
如果你的字符串实际上是超文本标记语言数据,你必须添加htmlentities($lump),这样它就不会返回空:
$lump = '<html><head></head><body>rtyfbytgyuibg-----start-----<div>isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r</div>-----end-----gcgkhjkn</body></html>';
$lump = htmlentities($lump) //<-- HERE
$start_tag = '-----start-----';
$end_tag = '-----end-----';
// method 1
if (preg_match('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
echo $matches[1];
}
// method 2 (faster)
$startpos = strpos($lump, $start_tag) + strlen($start_tag);
if ($startpos !== false) {
$endpos = strpos($lump, $end_tag, $startpos);
if ($endpos !== false) {
echo substr($lump, $startpos, $endpos - $startpos);
}
}
// method 3 (if you need to find multiple occurrences)
if (preg_match_all('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
print_r($matches[1]);
}
// method 4
$output = strstr( substr( $string, strpos( $string, $start) + strlen( $start)), $end, true);
//Turn back to regular HTML
echo htmlspecialchars_decode($output);https://stackoverflow.com/questions/11277620
复制相似问题