首页 经验

php endswith (2)

时间: 2024-09-08 07:56:25

(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)


在 PHP 中,如果您想检查一个字符串是否以特定的子字符串结尾,可以使用 str.endswith 函数。不过,由于 PHP 没有内置的 endswith 函数,我们通常使用 substrstrpos 函数来实现这一目的。


使用 substr

下面是一个使用 substr 函数检查字符串结尾的示例:


</code>php

<?php

function endsWith($string, $endString) {

    $length = strlen($endString);

    if ($length == 0) {

        return true; // 空字符串总是以任何字符串结尾

    }

    return (substr($string, -$length) === $endString);

}


// 示例用法

$string = "Hello, world!";

$endString = "world!";


if (endsWith($string, $endString)) {

    echo "字符串以 '{$endString}' 结尾。";

} else {

    echo "字符串不以 '{$endString}' 结尾。";

}

?>

</code>


使用 str_ends_with (PHP 8及以上)

如果您使用的是 PHP 8 或更高版本,可以直接使用 str_ends_with 函数,它是一个内置函数,能够简洁地检查字符串是否以特定子字符串结尾。


php

<?php

$string = "Hello, world!";

$endString = "world!";


if (str_ends_with($string, $endString)) {

    echo "字符串以 '{$endString}' 结尾。";

} else {

    echo "字符串不以 '{$endString}' 结尾。";

}

?>


总结

- 如果您使用的是 PHP 7 或更早的版本,您可以使用自定义的 endsWith 函数。

- 如果您使用的是 PHP 8 或以上版本,您可以直接使用 str_ends_with 函数,使代码更加简洁和易读。


文章列表 下一个 PHP str_ends_with 详解

最新

工具

© 2019-至今 适观科技

沪ICP备17002269号