StringUtil.php
61 lines
| 1 | <?php |
| 2 | /** |
| 3 | * A class of utilities for dealing with strings. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Utilities; |
| 7 | |
| 8 | /** |
| 9 | * A class of utilities for dealing with strings. |
| 10 | */ |
| 11 | final class StringUtil { |
| 12 | |
| 13 | /** |
| 14 | * Checks to see whether or not a string starts with another. |
| 15 | * |
| 16 | * @param string $string The string we want to check. |
| 17 | * @param string $starts_with The string we're looking for at the start of $string. |
| 18 | * @param bool $case_sensitive Indicates whether the comparison should be case-sensitive. |
| 19 | * |
| 20 | * @return bool True if the $string starts with $starts_with, false otherwise. |
| 21 | */ |
| 22 | public static function starts_with( string $string, string $starts_with, bool $case_sensitive = true ): bool { |
| 23 | $len = strlen( $starts_with ); |
| 24 | if ( $len > strlen( $string ) ) { |
| 25 | return false; |
| 26 | } |
| 27 | |
| 28 | $string = substr( $string, 0, $len ); |
| 29 | |
| 30 | if ( $case_sensitive ) { |
| 31 | return strcmp( $string, $starts_with ) === 0; |
| 32 | } |
| 33 | |
| 34 | return strcasecmp( $string, $starts_with ) === 0; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Checks to see whether or not a string ends with another. |
| 39 | * |
| 40 | * @param string $string The string we want to check. |
| 41 | * @param string $ends_with The string we're looking for at the end of $string. |
| 42 | * @param bool $case_sensitive Indicates whether the comparison should be case-sensitive. |
| 43 | * |
| 44 | * @return bool True if the $string ends with $ends_with, false otherwise. |
| 45 | */ |
| 46 | public static function ends_with( string $string, string $ends_with, bool $case_sensitive = true ): bool { |
| 47 | $len = strlen( $ends_with ); |
| 48 | if ( $len > strlen( $string ) ) { |
| 49 | return false; |
| 50 | } |
| 51 | |
| 52 | $string = substr( $string, -$len ); |
| 53 | |
| 54 | if ( $case_sensitive ) { |
| 55 | return strcmp( $string, $ends_with ) === 0; |
| 56 | } |
| 57 | |
| 58 | return strcasecmp( $string, $ends_with ) === 0; |
| 59 | } |
| 60 | } |
| 61 |