KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Check number of occurences in a string
PRODUCT: 4D | VERSION: 12.5 | PLATFORM: Mac & Win
Published On: June 11, 2013

Obatining the number of occurences of a particular character within a string can be easily obtained using the PHP command substr_count along with the 4D command PHP EXECUTE.

Create the following project method saved as UTIL_HowMany:

// UTIL_HowMany
C_TEXT($1) // input
C_TEXT($2) // count this
C_LONGINT($0)
If (Count parameters=2)
   C_BOOLEAN($ok)
   $ok:=PHP Execute("";"substr_count";$0;$1;$2)
Else
   $0:=0
End if


Once the project method is saved as UTIL_HowMany it can be used like this:
$a:="test, test, test"
$b:=","
$num:=UTIL_HowMany($a;$b)


The utility method could also be written using pure 4D commands like this:
// UTIL_HowMany
C_TEXT($1) // input
C_TEXT($2) // count this
C_LONGINT($0)
If (Count parameters=2)
   $0:=(Length($1)-(Length(Replace string($1;$2;""))))/Length($2)
Else
   $0:=0
End if