Checking the beginning of a string (prefix)
Posted on August 30, 2008, Filled under PHP,
Bookmark it
Greetings,
This is a function which will help you to determine if a text starts which a specific string. It’s useful when you’re working with dynamic variables and you need to check if the text matches some patterns like its beginning. For instance you have an array and you want to output only files that have a prefix.
<?php
// Credits: http://www.bitrepository.com/
function begins_with($str, $text)
{
$rest = substr($text, 0, strlen($str));
if($rest == $str)
{
return true;
}
else
{
return false;
}
}
/* It could be a dynamic variable. Some names, locations, phone numbers etc.
have a prefix and this function can check it. */
$text = '05670-123456789'; // a sample phone number
$begin_str = '05670';
$check = begins_with($begin_str, $text);
if($check)
{
echo '"'.$text.'"'.' begins with "'.$begin_str.'"';
}
?>
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- August 30, 2008
- article by Gabriel C.
- 1 comment
Related Posts
How to add a prefix to a field’s valueat August 30, 2008 with 1 comment
Validate numeric stringat May 21, 2008
How to make a selection based on the beginning valueat August 30, 2008
Format text into a SEO Friendly Stringat August 28, 2008 with 1 comment
PHP: Show alternate colors between rowsat August 27, 2008 with 3 comments

One Reply to "Checking the beginning of a string (prefix)"
August 30, 2008 at 11:54 AM
Smaller function:
function begins_with($str, $text)
{
return substr($text, 0, strlen($str)) == $str ? true:false;
}