함수 substrs after before

substr_after_before
substrings_after_before

1 Example[ | ]

  • syntaxhighlight
$str = "<!doctype html>
<html>
  <head>
    <title>Hello HTML</title>
  </head>
  <body>
    <p>Hello World!</p>
  </body>
</html>";
$output = gets_between('</', '>', $str);
  • output
Array
(
    [0] => title
    [1] => head
    [2] => p
    [3] => body
    [4] => html
)

2 C#[ | ]

using System.Text.RegularExpressions;

public static string[] gets_between(string start, string end, string str)
{
  Regex re = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));
  MatchCollection matches = re.Matches(str);
  return matches.Cast<Match>().Select(x => x.Groups[1].Value).ToArray();
}
public static string[] gets_between(string start, string end, string str)
{
  int str_len = str.Length;
  int end_len = end.Length;
  int start_len = start.Length;
  List<string> list = new List<string>();

  int pos = 0;
  int pos1, pos2;
  while (pos < (str_len - end_len))
  {
    pos1 = str.IndexOf(start, pos);
    if (pos1 < 0) break;
    pos1 += start_len;
    pos2 = str.IndexOf(end, pos1);
    if (pos2 < 0) break;
    list.Add(str.Substring(pos1, pos2 - pos1));
    pos = pos2 + end_len;
  }
  return list.ToArray();
}
using System.Text.RegularExpressions;

public static string[] gets_between(string start, string end, string str)
{
  Regex re = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end), RegexOptions.Multiline);
  MatchCollection matches = re.Matches(str);
  return matches.Cast<Match>().Select(x => x.Value).ToArray();
}

3 PHP[ | ]

function gets_between($start, $end, $str) {
  $start = preg_quote($start,'/');
  $end = preg_quote($end,'/');
  $pattern = '/'.$start.'([^'.$end.']*)'.$end.'/';
  preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER);
  return $matches[1];
}
function gets_between($start, $end, $str) {
  $str_len = strlen($str);  
  $start_len = strlen($start);
  $end_len = strlen($end);
  $arr = array();
  $pos = 0;
  while($pos < $str_len - $end_len) {  
    $pos1 = strpos($str, $start, $pos);
    if($pos1 === false || $pos1 < $pos) break;  
    $pos1 += $start_len;
    $pos2 = strpos($str, $end, $pos1);
	if($pos2 === false || $pos2 < $pos) break;
    $arr[] = substr($str, $pos1, $pos2-$pos1);
    $pos = $pos2 + $end_len;
  }
  return $arr;
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}