PHP 8 hat eine neue praktische String-Funktion str_starts_with(). In diesem Artikel werden die Einführung, Verwendung und Beispiele dieser Funktion vorgestellt.
str_starts_with() kann bestimmen, ob eine Zeichenfolge mit einer anderen Zeichenfolge beginnt, und einen booleschen Wert zurückgeben. Die Syntax lautet wie folgt:
str_starts_with(string $haystack , string $needle): bool
Parametererklärung:
$haystack< /. code>: Die Zeichenfolge, nach der gesucht werden soll. <code>$haystack
:要搜索的字符串。$needle
:被搜索的开头字符串。返回值:
$haystack
以 $needle
开头,则返回 true。$haystack
不以 $needle
$needle
: Die Startzeichenfolge, nach der gesucht wird. $haystack
mit $needle
beginnt, wird true zurückgegeben. Wenn $haystack
nicht mit $needle
beginnt, wird „false“ zurückgegeben.
<?php $haystack = 'Hello World'; $needle = 'Hello'; if (str_starts_with($haystack, $needle)) { echo "字符串 '{$haystack}' 以 '{$needle}' 开头。"; } else { echo "字符串 '{$haystack}' 没有以 '{$needle}' 开头。"; } // Output: 字符串 'Hello World' 以 'Hello' 开头。
<?php $haystack = 'Hello World'; $needle = 'hello'; if (str_starts_with(strtolower($haystack), strtolower($needle))) { echo "字符串 '{$haystack}' 以 '{$needle}' 开头(不区分大小写)。"; } else { echo "字符串 '{$haystack}' 没有以 '{$needle}' 开头(不区分大小写)。"; } // Output: 字符串 'Hello World' 以 'hello' 开头(不区分大小写)。
<?php $url = 'https://www.example.com'; $allowedUrls = ['https://www.example.com', 'https://www.example.org']; foreach ($allowedUrls as $allowedUrl) { if (str_starts_with($url, $allowedUrl)) { echo "URL '{$url}' 被允许。"; } } // Output: URL 'https://www.example.com' 被允许。
<?php $filename = 'example.php'; $allowedExtensions = ['php', 'html']; foreach ($allowedExtensions as $extension) { if (str_ends_with($filename, '.' . $extension)) { echo "文件 '{$filename}' 合法,扩展名为 '{$extension}'。"; } } // Output: 文件 'example.php' 合法,扩展名为 'php'。
Das obige ist der detaillierte Inhalt vonString-Funktionen in PHP8: So verwenden Sie str_starts_with(). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!