Jump to content

function for checking begg. and end of a string


dsaba

Recommended Posts

I searched google and php.net but I suppose I don't have the right keywords for what function I want

 

I wanted to ask if anyone knew the best method or best php function to read the begg. and end of a string.

 

for example:

$string = "<<hello world>>";

 

I want to make sure that the first 2 characters of this string are "<<"

I also want to make sure that the last 2 characters are ">>"

If this is not true then I want to reject or echo an error message.

 

I know how to check if certain characters exist in a string, and even replace them, but I want to check if certain characters exist in the begg. or end of a string.

 

-thanks in advance


function check_string($str)
{
$num = strlen($str)-2;
$begin = substr($str,0,2);
$end = substr($str,$num);
if (($begin == "<<")&&($end==">>"))
{
return true;
}
else
{
return false;
}
}

$string = "<<hello world>>";
if(check_string($string)
{
//do stuff in this case as it will return true on $string
}
else
{
//error message
}

thats what my check_function($string) does for you

 

function check_string($str) // pass the function the string to check
{
$num = strlen($str)-2; // count the number of characters in the string then assign the variable $num with this number - 2
$begin = substr($str,0,2); //strip out the first two characters and assign to $begin
$end = substr($str,$num); //strip out the last two characters and assign to $end
if (($begin == "<<")&&($end==">>")) 
{ 
return true;
}
else
{
return false;
}
}

is there also a way I can delete the rest of the string from << and on

 

for example:

$string = "<<hello world>>";

 

I want to keep "<<"

but delete the rest

 

also another thing I want to do is add on from there as well

for example:

$string = "<<hello world>>";

 

Only after the "<<" I want to add "hola mundo en espanol"

 

so the string will now read "<<hola mundo en espanol hello world>>"

 

can you show me an example with that?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.