Counting occurences of one string inside another

Saturday 4 April 2026 @ 5:08 pm

I’ve been battling some unusual web traffic on my site. I get thousands of hits every day from random IP addresses and all of them look something like this:

GET /newsletter/consulting/otherlinks/public/support/support/default.html

The string is made up of actual folder names on my site, but they are combined in random order and a random page is on the end. I am told this is penetration testing by a hacker bot.  Great.

While working on this problem I wanted a way to count the number of slashes in each request. Crystal doesn’t have a direct function for doing that, but after giving it some thought I found a relatively simple solution. I could:

  • calculate the length of the string,
  • replace all the slashes with an empty string (“”)
  • recalculate the length of the shorter string.
  • Subtract one length from the other to get the difference

That can even be used to count occurrences of a multiple character string. You would just have to divide the character difference by the number of characters in the target string. So I turned this into a generic formula (see below). You can plug in your field name and target string in the first two lines and it does the rest:

Local stringVar Field := {Table.Field};
Local stringVar Target := '/';Local numberVar x := Length(Field);
Local numberVar y := length (Replace (Field, Target, ''));
Local NumberVar z := length (Target);
(x-y) / z

Update 4/25/2026:

After posting the above I heard from my long time colleague, Ido Millet.  He shared an even simpler way to accomplish this:

Count(Split({Table.Field}, "/")) - 1

As with the original formula, your target string can be any length.

(For examples of my most popular formulas, please visit the FORMULAS page on my website.)






Comments are closed.

Recrystallize Pro