Counting characters...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jorgamun
Forum Newbie
Posts: 2
Joined: Sun Mar 25, 2007 2:06 pm

Counting characters...

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

jorgamun
Forum Newbie
Posts: 2
Joined: Sun Mar 25, 2007 2:06 pm

Post by jorgamun »

That answers my first question! Thanks! But any way to make that apply to the rest?
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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]);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

strpos() is the answer to all of the questions.
Post Reply