Home:ALL Converter>Get the last character before a specific part of string in PHP

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

Ask Time:2013-09-09T20:26:08         Author:István Pálinkás

Json Formatter

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
}

Author:István Pálinkás,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18698187/get-the-last-character-before-a-specific-part-of-string-in-php
user1646111 :

Simple way:\n\n$string = \"finding last charactor before this word!\";\n$target = ' word';//note the space\n\nif(strpos($string, $target) !== false){\n echo \"space found \";\n}\n",
2013-09-09T12:32:54
Tim S. :

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.\n\nfunction char_before($haystack, $needle) {\n // get index of needle\n $p = strpos($haystack, $needle);\n // needle not found or at the beginning\n if($p <= 0) return false;\n // get character before needle\n return substr($hackstack, $p - 1, 1);\n}\n\n\nImplementation:\n\n$test1 = 'this is a test';\n$test2 = 'is this a test?';\n\nif(char_before($test1, 'is') === ' ') // true\nif(char_before($test2, 'is') === ' ') // false\n\n\nPS. I tactically refused to use a regular expression because they are too slow.",
2013-09-09T12:32:22
yy