Count characters in a string from a search made in the string itself

Asked

Viewed 252 times

-1

Good afternoon to you all! I would like your help to find out how I count characters in a string, passing a reference in the string itself, for example: I have the string 19:30 and wanted that after the : check if the number of characters is greater than 2, if it is, would do one thing, if it would not do another. I know how to do the conditions part, I’m just bumping into that doubt, how to count characters after a reference. Thanks in advance!

  • If the "separator" character is unique within the string, you can use a burst and then a strlen. $Exp = explode(":", $string); $account = strlen($Exp[1]); ---- EDITING -- I was afraid to leave it incomplete, as you said the rest was ok. But it follows: if($account > 2){ does one thing }Else{ does another thing }

1 answer

1


you can use the function strpos() php, it finds the position of the first occurrence of a substring in the string. If no occurrence is found, this function returns false.

The solution for you is this:

$string =  '19:30';

$pos    =  strpos( $string, ':' );

if( !is_bool( $pos ) ) {
    $pos += 1;
    echo strlen( substr( $string, $pos) );
}

I hope it helps.

  • Thank you @Duque, as you said, was the solution! Thank you really! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.