程序go 2009-05-07 12:14 采纳率: 100%
浏览 595
已采纳

在 PHP 中使用 startsWith ()和 endsWith ()函数

How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?

For example:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true

转载于:https://stackoverflow.com/questions/834303/startswith-and-endswith-functions-in-php

  • 写回答

30条回答 默认 最新

  • lrony* 2009-05-07 12:24
    关注
    function startsWith($haystack, $needle)
    {
         $length = strlen($needle);
         return (substr($haystack, 0, $length) === $needle);
    }
    
    function endsWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }
    
        return (substr($haystack, -$length) === $needle);
    }
    

    Use this if you don't want to use a regex.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python