Search code examples
phpsubstr

Ignoring spces in substr()


I am using a substr() to get the last digits from a number. However, it takes spaces into consideration too. Is there a way to avoid it? Using preg_replace to remove spaces first is not an option, since I want them (spaces) in the outcome.

substr($match[0], -5)

To give you an example how it looks now:

123456789 - the numbers 56789 will show

1234 56 78 9 - depending where the spaces are it may show nothing or 78 or 7 or 9, etc.


Solution

  • you can remove the spaces before calling substr

    substr(str_replace(" ", "", $match[0]), -5)
    

    Or, if you want preserve spaces

    function RightSubstrIgnoreChar($string, $length, $IgnoreChar = ' ') {
        $r = "";
        for ($n = strlen($string) - 1; $n >= 0 && strlen(str_replace($IgnoreChar, "", $r)) < $length; $n--) {
            $r = substr($string, $n, 1) . $r;
        }
        return $r;
    }
    
    echo RightSubstrIgnoreChar("1234 56 78 9", 5);
    

    Output

    56 78 9