简体   繁体   中英

Count characters from string position x to string position y

how do i find how many characters are between the position of a string to another

For example the string might be: brown fox

How do i find how many characters are between 'r' and 'f'?

Thanks in advance

$r_pos = strpos($str, 'r');
$distance = strpos($str, 'f', $r_pos) - $r_pos - 1;
echo $distance;

Using strpos ( or stripos for case- insensitive searching), get the position of "r", and the position of "f". Then, subtract the two.

$phrase = "brown fox";
echo stripos( $phrase, "f" ) - stripos( $phrase, "r" );

If your sentence can contain an "f" prior to an "r", you can provide an offset for the "f" by passing in the position of "r" as the third argument to stripos :

$r = stripos( $phrase, "r" );
$f = stripos( $phrase, "f", $r );

echo $f - $r;
$str = "brown fox";
strpos($str,'f') - strpos($str,'r');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM