簡體   English   中英

獲取字符串中兩個標簽之間的所有內容

[英]Get ALL content between two tags in a string

我正在使用我在 SO 上找到的自定義 PHP function。 該函數的目的是查找標簽之間的內容,並將它們替換為str_ireplace 這是 function:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = stripos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = stripos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

我最近發現當我調用 function 時,它只找到第一次出現。 即我希望它找到每個<tag></tag>之間的所有東西,但它只找到第一個<tag></tag>之間的內容。 有人可以幫忙嗎?

這是幾個月前我為這個問題寫的 function。 您必須根據返回的 $pos 使用偏移量多次調用 function 以獲得所有准確度。 我希望這是可以接受的。

/* getSubstring
   returns a substring between string_before and string_after,
   starts to search at the offset. character of source
   returns an array: ['text'] = string found
                     ['pos'] = starting position of string_before within source
   returns text = '' and pos = false if string is not found
   example: $key = get_substring('12345here67890', '12345','67890')[0];
*/

function getSubstring($source, $string_before, $string_after, $offset = 0, $includeEnvelope = false) {
   if (strlen($source)<$offset)
      return(array('text' => '', 'pos' => false)); // kind of silly, but prevents an 'Offset not contained in string' warning
   $pos1 = strpos($source, $string_before, $offset);
   $sb_len = strlen($string_before);
   if ($pos1===false) {
      $result = '';
   }
   else {
      $pos2 = strpos($source, $string_after, $pos1 + strlen($string_before));
      if ($pos2===false) {
         $result = '';
         $pos1 = false;
      }
      else {
         $result = substr($source, $pos1 + $sb_len, $pos2 - $pos1 - $sb_len);
         if ($includeEnvelope)
            $result = $string_before.$result.$string_after;
     }
   }
   return (array('text' => $result, 'pos' => $pos1));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM