Page 1 of 1

Counting characters...

Posted: Sun Mar 25, 2007 2:16 pm
by jorgamun
I was wondering if there is a way to count characters given specific conditions. I need the methods for doing the following:

146381236x68321676814x

How would I count the characters from the beginning of the string to x? In this example, it would be 9.
What about in between x and x? In this example, it would be 11.
How could I take the sum of the first characters before x? In this example, it would be 34.
What about in between x and x? In this example, it would be 52.
How could I find the ratio of the characters before x and the characters between x and x, each counted respectively? In this example, it would be 9:11.

I worded these the best that I could... please help if you know! Thanks for your time.

Posted: Sun Mar 25, 2007 3:00 pm
by feyd

Posted: Sun Mar 25, 2007 3:35 pm
by jorgamun
That answers my first question! Thanks! But any way to make that apply to the rest?

Posted: Sun Mar 25, 2007 3:58 pm
by Skara
There may be an easier way to do this, but..
--assuming the format is digits + x + digits + x--

Code: Select all

$string = "146381236x68321676814x";
preg_match('/^(\d+?)x(\d+?)x$/',$string,$matches);

//How would I count the characters from the beginning of the string to x?
$count = count($matches[1]);

//How could I take the sum of the first characters before x?
$nums = explode('',$matches[1]);
$sum = 0;
foreach ($nums as $num) $sum += $num;

//What about in between x and x?
$nums = explode('',$matches[2]);
$sum = 0;
foreach ($nums as $num) $sum += $num;

//How could I find the ratio of the characters before x and the characters between x and x, each counted respectively?
$ratio = count($matches[1]) / count($matches[2]);

Posted: Mon Mar 26, 2007 9:09 am
by feyd
strpos() is the answer to all of the questions.