获取 PHP 中字符串特定部分之前的最后一个字符


Get the last character before a specific part of string in PHP

我需要一种方法来获取字符串中特定子字符串之前的最后一个字符。我需要这个来检查它是否是特定子字符串之前的空格。

我正在寻找这样的功能:

function last_character_before( $before_what , $in_string )
{
    $p = strpos( $before_what , $in_string );
    // $character_before =  somehow get the character before
    return $character_before;
}
if( $last_character_before( $keyword , $long_string ) )
{
    // Do something
}
else
{
    // Do something
}

如果你有匹配针的位置,你只需要减去 - 1 就可以得到在此之前的字符。如果位置为 -1 或 0,则前面没有字符。

function char_before($haystack, $needle) {
    // get index of needle
    $p = strpos($haystack, $needle);
    // needle not found or at the beginning
    if($p <= 0) return false;
    // get character before needle
    return substr($hackstack, $p - 1, 1);
}

实现:

$test1 = 'this is a test';
$test2 = 'is this a test?';
if(char_before($test1, 'is') === ' ') // true
if(char_before($test2, 'is') === ' ') // false

附言。我在战术上拒绝使用正则表达式,因为它们太慢了。

简单的方法:

$string = "finding last charactor before this word!";
$target = ' word';//note the space
if(strpos($string, $target) !== false){
 echo "space found ";
}
function last_character_before( $before_what , $in_string )
{
    $p = strpos( $before_what , $in_string );
    $character_before = substr(substr($in_string ,0,$p),-1);
    return $character_before;
}