Checking the beginning of a string (prefix)

Posted on August 30, 2008, 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!

Get our RSS Feed!

Related Posts

One Reply to "Checking the beginning of a string (prefix)"

  1. Smaller function:

    function begins_with($str, $text)
    {
    return substr($text, 0, strlen($str)) == $str ? true:false;
    }

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)