【问题标题】:Determining if string ends with another string [duplicate]确定字符串是否以另一个字符串结尾[重复]
【发布时间】:2014-02-09 07:27:09
【问题描述】:

如何确定字符串是否出现在另一个字符串的末尾。如果他们这样做,则将 true 打印到标准输出,如果他们不这样做,则打印 false。 strpos 会有所帮助吗?

    Sample Input

S1: “staff”
S2: “FF”

我将如何创建一个函数来运行它,

  function matching_ends($s1,$s2){

}

【问题讨论】:

标签: php


【解决方案1】:
<?php
$s1="testing";
$s2="ing";

echo matching_ends($s1, $s2);

function matching_ends($s1,$s2){
    return substr($s1, -strlen($s2)) == $s2 ? "true" : "false";
}
?>

Demo

【讨论】:

    【解决方案2】:

    你可以用这个

    if( substr($s1, strlen($s1)-1) === substr($s2, strlen($s2)-1))
    {
         // Do something when character at the last matches
    }
    else{
         // Do something when doesn't match
    }
    

    【讨论】:

    • @Hanky Panky 有更好的答案。我的代码仅用于匹配最后一个字符。我问错了。 :)
    • 那为什么不删除帖子;)
    • 你也可以只使用-1 而不是在那里使用strlen
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2015-07-10
    • 2013-09-04
    相关资源
    最近更新 更多