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

I would need a method to get the last character before a specific substring in a string. I need this to check if it's a SPACE before the specific substring, or not.

I am looking for a function like:

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
}

Upvotes: 0

Views: 899

Answers (3)

Tim S.
Tim S.

Reputation: 13843

If you have the position of matched needle, you just have to substract - 1 to get the character before that. If the position is -1 or 0, there's no character before.

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);
}

Implementation:

$test1 = 'this is a test';
$test2 = 'is this a test?';

if(char_before($test1, 'is') === ' ') // true
if(char_before($test2, 'is') === ' ') // false

PS. I tactically refused to use a regular expression because they are too slow.

Upvotes: 2

Essam Elmasry
Essam Elmasry

Reputation: 1252

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;
}

Upvotes: 0

user1646111
user1646111

Reputation:

Simple way:

$string = "finding last charactor before this word!";
$target = ' word';//note the space

if(strpos($string, $target) !== false){
 echo "space found ";
}

Upvotes: 0

Related Questions