函数文档

extract_from_markers()

💡 云策文档标注

概述

extract_from_markers() 函数用于从 .htaccess 文件中提取位于 BEGIN 和 END 标记之间的字符串。它接受文件名和标记作为参数,返回一个字符串数组。

关键要点

  • 函数从指定文件中提取 BEGIN 和 END 标记之间的内容。
  • 参数 $filename 为必需的文件名字符串,$marker 为必需的标记字符串。
  • 返回值为字符串数组,包含提取的行,忽略以 # 开头的注释行。
  • 如果文件不存在,函数返回空数组。

代码示例

function extract_from_markers( $filename, $marker ) {
    $result = array();

    if ( ! file_exists( $filename ) ) {
        return $result;
    }

    $markerdata = explode( "n", implode( '', file( $filename ) ) );

    $state = false;

    foreach ( $markerdata as $markerline ) {
        if ( str_contains( $markerline, '# END ' . $marker ) ) {
            $state = false;
        }

        if ( $state ) {
            if ( str_starts_with( $markerline, '#' ) ) {
                continue;
            }

            $result[] = $markerline;
        }

        if ( str_contains( $markerline, '# BEGIN ' . $marker ) ) {
            $state = true;
        }
    }

    return $result;
}

注意事项

  • 函数在 WordPress 1.5.0 版本中引入。
  • 确保文件路径正确,否则可能返回空结果。
  • 标记格式为 # BEGIN marker 和 # END marker,区分大小写。

📄 原文内容

Extracts strings from between the BEGIN and END markers in the .htaccess file.

Parameters

$filenamestringrequired
Filename to extract the strings from.
$markerstringrequired
The marker to extract the strings from.

Return

string[] An array of strings from a file (.htaccess) from between BEGIN and END markers.

Source

function extract_from_markers( $filename, $marker ) {
	$result = array();

	if ( ! file_exists( $filename ) ) {
		return $result;
	}

	$markerdata = explode( "n", implode( '', file( $filename ) ) );

	$state = false;

	foreach ( $markerdata as $markerline ) {
		if ( str_contains( $markerline, '# END ' . $marker ) ) {
			$state = false;
		}

		if ( $state ) {
			if ( str_starts_with( $markerline, '#' ) ) {
				continue;
			}

			$result[] = $markerline;
		}

		if ( str_contains( $markerline, '# BEGIN ' . $marker ) ) {
			$state = true;
		}
	}

	return $result;
}

Changelog

Version Description
1.5.0 Introduced.