PHP makes working with strings quite easy but if you simply want to check if a string starts with, ends with or contains another string there are no functions that give you a simple true
or false
.
So, here they are. To understand what mb_internal_encoding('UTF-8');
does and why you should use it read my earlier blog post “What you need to know about PHP’s internal character encoding“.
<?php
function stringStartsWith($string, $subString, $caseSensitive = true) {
if ($caseSensitive === false) {
$string = mb_strtolower($string);
$subString = mb_strtolower($subString);
}
if (mb_substr($string, 0, mb_strlen($subString)) == $subString) {
return true;
} else {
return false;
}
}
function stringEndsWith($string, $subString, $caseSensitive = true) {
if ($caseSensitive === false) {
$string = mb_strtolower($string);
$subString = mb_strtolower($subString);
}
$strlen = strlen($string);
$subStringLength = strlen($subString);
if ($subStringLength > $strlen) {
return false;
}
return substr_compare($string, $subString, $strlen - $subStringLength, $subStringLength) === 0;
}
function stringContains($haystack, $needle, $caseSensitive = true) {
if ($caseSensitive === false) {
$haystack = mb_strtolower($haystack);
$needle = mb_strtolower($needle);
}
if (mb_substr_count($haystack, $needle) > 0) {
return true;
} else {
return false;
}
}
mb_internal_encoding('UTF-8');
echo '<pre>';
echo 'Case-sensitive:';
var_dump(stringStartsWith('Foo bar', 'Fo')); // true
var_dump(stringStartsWith('Bar', 'Foo bar')); // false
var_dump(stringEndsWith('Foo bar', 'ar')); // true
var_dump(stringEndsWith('Foo bar', 'foo')); // false
var_dump(stringContains('Foo bar', 'o b')); // true
var_dump(stringContains('Foo bar', 'blah')); // false
echo PHP_EOL . 'Case-insensitive:' . PHP_EOL;
var_dump(stringStartsWith('FOO BAR', 'fo', false)); // true
var_dump(stringEndsWith('FOO BAR', 'ar', false)); // true
var_dump(stringContains('FOO BAR', 'o b', false)); // true
echo '</pre>';
?>
Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from
Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.